| | | 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.Localization; |
| | | 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 | | using Kestrun.OpenApi; |
| | | 26 | | using Microsoft.AspNetCore.Antiforgery; |
| | | 27 | | using Kestrun.Callback; |
| | | 28 | | using System.Text.Json; |
| | | 29 | | using System.Text.Json.Serialization; |
| | | 30 | | using Microsoft.OpenApi; |
| | | 31 | | using System.Text.Json.Nodes; |
| | | 32 | | using Kestrun.Forms; |
| | | 33 | | |
| | | 34 | | namespace Kestrun.Hosting; |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Provides hosting and configuration for the Kestrun application, including service registration, middleware setup, an |
| | | 38 | | /// </summary> |
| | | 39 | | public partial class KestrunHost : IDisposable |
| | | 40 | | { |
| | | 41 | | private const string KestrunVariableMarkerKey = "__kestrunVariable"; |
| | | 42 | | |
| | | 43 | | #region Static Members |
| | | 44 | | private static readonly JsonSerializerOptions JsonOptions; |
| | | 45 | | |
| | | 46 | | static KestrunHost() |
| | | 47 | | { |
| | 1 | 48 | | JsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) |
| | 1 | 49 | | { |
| | 1 | 50 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| | 1 | 51 | | WriteIndented = false |
| | 1 | 52 | | }; |
| | 1 | 53 | | JsonOptions.Converters.Add(new JsonStringEnumConverter()); |
| | 1 | 54 | | } |
| | | 55 | | #endregion |
| | | 56 | | |
| | | 57 | | #region Fields |
| | 2970 | 58 | | internal WebApplicationBuilder Builder { get; } |
| | | 59 | | |
| | | 60 | | private WebApplication? _app; |
| | | 61 | | |
| | 131 | 62 | | internal WebApplication App => _app ?? throw new InvalidOperationException("WebApplication is not built yet. Call Bu |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Gets the runtime information for the Kestrun host. |
| | | 66 | | /// </summary> |
| | 725 | 67 | | public KestrunHostRuntime Runtime { get; } = new(); |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Gets the application name for the Kestrun host. |
| | | 71 | | /// </summary> |
| | 2 | 72 | | public string ApplicationName => Options.ApplicationName ?? "KestrunApp"; |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Gets the configuration options for the Kestrun host. |
| | | 76 | | /// </summary> |
| | 2019 | 77 | | public KestrunOptions Options { get; private set; } = new(); |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// List of PowerShell module paths to be loaded. |
| | | 81 | | /// </summary> |
| | 636 | 82 | | private readonly List<string> _modulePaths = []; |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Indicates whether the Kestrun host is stopping. |
| | | 86 | | /// </summary> |
| | | 87 | | private int _stopping; // 0 = running, 1 = stopping |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Indicates whether the Kestrun host configuration has been applied. |
| | | 91 | | /// </summary> |
| | 507 | 92 | | public bool IsConfigured { get; private set; } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// The runspace pool manager for PowerShell execution. |
| | | 96 | | /// </summary> |
| | | 97 | | private KestrunRunspacePoolManager? _runspacePool; |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Status code options for configuring status code pages. |
| | | 101 | | /// </summary> |
| | | 102 | | private StatusCodeOptions? _statusCodeOptions; |
| | | 103 | | /// <summary> |
| | | 104 | | /// Exception options for configuring exception handling. |
| | | 105 | | /// </summary> |
| | | 106 | | private ExceptionOptions? _exceptionOptions; |
| | | 107 | | private string? _powerShellErrorResponseScript; |
| | | 108 | | /// <summary> |
| | | 109 | | /// Forwarded headers options for configuring forwarded headers handling. |
| | | 110 | | /// </summary> |
| | | 111 | | private ForwardedHeadersOptions? _forwardedHeaderOptions; |
| | | 112 | | |
| | 8 | 113 | | internal KestrunRunspacePoolManager RunspacePool => _runspacePool ?? throw new InvalidOperationException("Runspace p |
| | | 114 | | |
| | | 115 | | // ── ✦ QUEUE #1 : SERVICE REGISTRATION ✦ ───────────────────────────── |
| | 636 | 116 | | private readonly List<Action<IServiceCollection>> _serviceQueue = []; |
| | | 117 | | |
| | | 118 | | // ── ✦ QUEUE #2 : MIDDLEWARE STAGES ✦ ──────────────────────────────── |
| | 636 | 119 | | private readonly List<Action<IApplicationBuilder>> _middlewareQueue = []; |
| | | 120 | | |
| | 749 | 121 | | internal List<Action<KestrunHost>> FeatureQueue { get; } = []; |
| | | 122 | | |
| | 816 | 123 | | internal List<IProbe> HealthProbes { get; } = []; |
| | | 124 | | #if NET9_0_OR_GREATER |
| | | 125 | | private readonly Lock _healthProbeLock = new(); |
| | | 126 | | #else |
| | 636 | 127 | | private readonly object _healthProbeLock = new(); |
| | | 128 | | #endif |
| | | 129 | | |
| | 636 | 130 | | internal readonly Dictionary<(string Pattern, HttpVerb Method), MapRouteOptions> _registeredRoutes = |
| | 636 | 131 | | #pragma warning disable IDE0028 // Simplify collection initialization |
| | 636 | 132 | | new(new RouteKeyComparer()); |
| | | 133 | | #pragma warning restore IDE0028 // Simplify collection initialization |
| | | 134 | | |
| | | 135 | | //internal readonly Dictionary<(string Scheme, string Type), AuthenticationSchemeOptions> _registeredAuthentications |
| | | 136 | | // new(new AuthKeyComparer()); |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Gets the root directory path for the Kestrun application. |
| | | 140 | | /// </summary> |
| | 149 | 141 | | public string? KestrunRoot { get; private set; } |
| | | 142 | | |
| | | 143 | | /// <summary> |
| | | 144 | | /// Gets the collection of module paths to be loaded by the Kestrun host. |
| | | 145 | | /// </summary> |
| | 0 | 146 | | public List<string> ModulePaths => _modulePaths; |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Gets the shared state store for managing shared data across requests and sessions. |
| | | 150 | | /// </summary> |
| | 206 | 151 | | public SharedState.SharedState SharedState { get; } |
| | | 152 | | |
| | | 153 | | /// <summary> |
| | | 154 | | /// Gets the Serilog logger instance used by the Kestrun host. |
| | | 155 | | /// </summary> |
| | 12182 | 156 | | public Serilog.ILogger Logger { get; private set; } |
| | | 157 | | |
| | | 158 | | private SchedulerService? _scheduler; |
| | | 159 | | /// <summary> |
| | | 160 | | /// Gets the scheduler service used for managing scheduled tasks in the Kestrun host. |
| | | 161 | | /// Initialized in ConfigureServices via AddScheduler() |
| | | 162 | | /// </summary> |
| | | 163 | | public SchedulerService Scheduler |
| | | 164 | | { |
| | 1 | 165 | | get => _scheduler ?? throw new InvalidOperationException("SchedulerService is not initialized. Call AddScheduler |
| | 1 | 166 | | internal set => _scheduler = value; |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private KestrunTaskService? _tasks; |
| | | 170 | | /// <summary> |
| | | 171 | | /// Gets the ad-hoc task service used for running one-off tasks (PowerShell, C#, VB.NET). |
| | | 172 | | /// Initialized via AddTasks() |
| | | 173 | | /// </summary> |
| | | 174 | | public KestrunTaskService Tasks |
| | | 175 | | { |
| | 0 | 176 | | get => _tasks ?? throw new InvalidOperationException("Tasks is not initialized. Call AddTasks() to enable task m |
| | 0 | 177 | | internal set => _tasks = value; |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Gets the stack used for managing route groups in the Kestrun host. |
| | | 182 | | /// </summary> |
| | 636 | 183 | | public System.Collections.Stack RouteGroupStack { get; } = new(); |
| | | 184 | | |
| | | 185 | | /// <summary> |
| | | 186 | | /// Gets the registered routes in the Kestrun host. |
| | | 187 | | /// </summary> |
| | 179 | 188 | | public Dictionary<(string, HttpVerb), MapRouteOptions> RegisteredRoutes => _registeredRoutes; |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Gets the registered authentication schemes in the Kestrun host. |
| | | 192 | | /// </summary> |
| | 659 | 193 | | public AuthenticationRegistry RegisteredAuthentications { get; } = new(); |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Gets or sets the default cache control settings for HTTP responses. |
| | | 197 | | /// </summary> |
| | 9 | 198 | | public CacheControlHeaderValue? DefaultCacheControl { get; internal set; } |
| | | 199 | | |
| | | 200 | | /// <summary> |
| | | 201 | | /// Gets the shared state manager for managing shared data across requests and sessions. |
| | | 202 | | /// </summary> |
| | 130 | 203 | | public bool PowershellMiddlewareEnabled { get; set; } = false; |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// The localization store used by this host when `UseKestrunLocalization` is configured. |
| | | 207 | | /// May be null if localization middleware was not added. |
| | | 208 | | /// </summary> |
| | 0 | 209 | | public KestrunLocalizationStore? LocalizationStore { get; internal set; } |
| | | 210 | | |
| | | 211 | | /// <summary> |
| | | 212 | | /// Gets or sets a value indicating whether this instance is the default Kestrun host. |
| | | 213 | | /// </summary> |
| | 1 | 214 | | public bool DefaultHost { get; internal set; } |
| | | 215 | | |
| | | 216 | | /// <summary> |
| | | 217 | | /// The list of CORS policy names that have been defined in the KestrunHost instance. |
| | | 218 | | /// </summary> |
| | 820 | 219 | | public List<string> DefinedCorsPolicyNames { get; } = []; |
| | | 220 | | |
| | | 221 | | /// <summary> |
| | | 222 | | /// Gets or sets a value indicating whether CORS (Cross-Origin Resource Sharing) is enabled. |
| | | 223 | | /// </summary> |
| | 156 | 224 | | public bool CorsPolicyDefined => DefinedCorsPolicyNames.Count > 0; |
| | | 225 | | |
| | | 226 | | /// <summary> |
| | | 227 | | /// Gets the scanned OpenAPI component annotations from PowerShell scripts. |
| | | 228 | | /// </summary> |
| | 63 | 229 | | public Dictionary<string, OpenApiComponentAnnotationScanner.AnnotatedVariable>? ComponentAnnotations { get; private |
| | | 230 | | |
| | | 231 | | /// <summary> |
| | | 232 | | /// Gets or sets the status code options for configuring status code pages. |
| | | 233 | | /// </summary> |
| | | 234 | | public StatusCodeOptions? StatusCodeOptions |
| | | 235 | | { |
| | 110 | 236 | | get => _statusCodeOptions; |
| | | 237 | | set |
| | | 238 | | { |
| | 0 | 239 | | if (IsConfigured) |
| | | 240 | | { |
| | 0 | 241 | | throw new InvalidOperationException("Cannot modify StatusCodeOptions after configuration is applied."); |
| | | 242 | | } |
| | 0 | 243 | | _statusCodeOptions = value; |
| | 0 | 244 | | } |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | /// <summary> |
| | | 248 | | /// Gets or sets the exception options for configuring exception handling. |
| | | 249 | | /// </summary> |
| | | 250 | | public ExceptionOptions? ExceptionOptions |
| | | 251 | | { |
| | 123 | 252 | | get => _exceptionOptions; |
| | | 253 | | set |
| | | 254 | | { |
| | 5 | 255 | | if (IsConfigured) |
| | | 256 | | { |
| | 0 | 257 | | throw new InvalidOperationException("Cannot modify ExceptionOptions after configuration is applied."); |
| | | 258 | | } |
| | 5 | 259 | | _exceptionOptions = value; |
| | 5 | 260 | | } |
| | | 261 | | } |
| | | 262 | | |
| | | 263 | | /// <summary> |
| | | 264 | | /// Gets or sets an optional PowerShell script used by PowerShell route execution to generate error responses. |
| | | 265 | | /// The script executes in the request runspace and is responsible for writing the response. |
| | | 266 | | /// </summary> |
| | | 267 | | public string? PowerShellErrorResponseScript |
| | | 268 | | { |
| | 2 | 269 | | get => _powerShellErrorResponseScript; |
| | | 270 | | set |
| | | 271 | | { |
| | 2 | 272 | | if (IsConfigured) |
| | | 273 | | { |
| | 0 | 274 | | throw new InvalidOperationException("Cannot modify PowerShellErrorResponseScript after configuration is |
| | | 275 | | } |
| | | 276 | | |
| | 2 | 277 | | _powerShellErrorResponseScript = value; |
| | 2 | 278 | | } |
| | | 279 | | } |
| | | 280 | | |
| | | 281 | | /// <summary> |
| | | 282 | | /// Gets or sets the forwarded headers options for configuring forwarded headers handling. |
| | | 283 | | /// </summary> |
| | | 284 | | public ForwardedHeadersOptions? ForwardedHeaderOptions |
| | | 285 | | { |
| | 113 | 286 | | get => _forwardedHeaderOptions; |
| | | 287 | | set |
| | | 288 | | { |
| | 4 | 289 | | if (IsConfigured) |
| | | 290 | | { |
| | 1 | 291 | | throw new InvalidOperationException("Cannot modify ForwardedHeaderOptions after configuration is applied |
| | | 292 | | } |
| | 3 | 293 | | _forwardedHeaderOptions = value; |
| | 3 | 294 | | } |
| | | 295 | | } |
| | | 296 | | |
| | | 297 | | /// <summary> |
| | | 298 | | /// Gets the antiforgery options for configuring antiforgery token generation and validation. |
| | | 299 | | /// </summary> |
| | 0 | 300 | | public AntiforgeryOptions? AntiforgeryOptions { get; set; } |
| | | 301 | | |
| | | 302 | | /// <summary> |
| | | 303 | | /// Gets the OpenAPI document descriptor for configuring OpenAPI generation. |
| | | 304 | | /// </summary> |
| | 747 | 305 | | public Dictionary<string, OpenApiDocDescriptor> OpenApiDocumentDescriptor { get; } = []; |
| | | 306 | | |
| | | 307 | | /// <summary> |
| | | 308 | | /// Gets the IDs of all OpenAPI documents configured in the Kestrun host. |
| | | 309 | | /// </summary> |
| | 0 | 310 | | public string[] OpenApiDocumentIds => [.. OpenApiDocumentDescriptor.Keys]; |
| | | 311 | | |
| | | 312 | | /// <summary> |
| | | 313 | | /// Gets the default OpenAPI document descriptor. |
| | | 314 | | /// </summary> |
| | | 315 | | public OpenApiDocDescriptor? DefaultOpenApiDocumentDescriptor |
| | 0 | 316 | | => OpenApiDocumentDescriptor.FirstOrDefault().Value; |
| | | 317 | | |
| | | 318 | | #endregion |
| | | 319 | | |
| | | 320 | | // Accepts optional module paths (from PowerShell) |
| | | 321 | | #region Constructor |
| | | 322 | | |
| | | 323 | | /// <summary> |
| | | 324 | | /// Initializes a new instance of the <see cref="KestrunHost"/> class with the specified application name, root dire |
| | | 325 | | /// </summary> |
| | | 326 | | /// <param name="appName">The name of the application.</param> |
| | | 327 | | /// <param name="kestrunRoot">The root directory for the Kestrun application.</param> |
| | | 328 | | /// <param name="modulePathsObj">An array of module paths to be loaded.</param> |
| | | 329 | | public KestrunHost(string? appName, string? kestrunRoot = null, string[]? modulePathsObj = null) : |
| | 108 | 330 | | this(appName, Log.Logger, kestrunRoot, modulePathsObj) |
| | 108 | 331 | | { } |
| | | 332 | | |
| | | 333 | | /// <summary> |
| | | 334 | | /// Initializes a new instance of the <see cref="KestrunHost"/> class with the specified application name and logger |
| | | 335 | | /// </summary> |
| | | 336 | | /// <param name="appName">The name of the application.</param> |
| | | 337 | | /// <param name="logger">The Serilog logger instance to use.</param> |
| | | 338 | | /// <param name="ordinalIgnoreCase">Indicates whether the shared state should be case-insensitive.</param> |
| | | 339 | | public KestrunHost(string? appName, Serilog.ILogger logger, |
| | 0 | 340 | | bool ordinalIgnoreCase) : this(appName, logger, null, null, null, ordinalIgnoreCase) |
| | 0 | 341 | | { } |
| | | 342 | | |
| | | 343 | | /// <summary> |
| | | 344 | | /// Initializes a new instance of the <see cref="KestrunHost"/> class with the specified application name, logger, r |
| | | 345 | | /// </summary> |
| | | 346 | | /// <param name="appName">The name of the application.</param> |
| | | 347 | | /// <param name="logger">The Serilog logger instance to use.</param> |
| | | 348 | | /// <param name="kestrunRoot">The root directory for the Kestrun application.</param> |
| | | 349 | | /// <param name="modulePathsObj">An array of module paths to be loaded.</param> |
| | | 350 | | /// <param name="args">Command line arguments to pass to the application.</param> |
| | | 351 | | /// <param name="ordinalIgnoreCase">Indicates whether the shared state should be case-insensitive.</param> |
| | 636 | 352 | | public KestrunHost(string? appName, Serilog.ILogger logger, |
| | 636 | 353 | | string? kestrunRoot = null, string[]? modulePathsObj = null, string[]? args = null, bool ordinalIgnoreCase = true) |
| | | 354 | | { |
| | | 355 | | // ① Logger |
| | 636 | 356 | | Logger = logger ?? Log.Logger; |
| | 636 | 357 | | LogConstructorArgs(appName, logger == null, kestrunRoot, modulePathsObj?.Length ?? 0); |
| | 636 | 358 | | SharedState = new(ordinalIgnoreCase: ordinalIgnoreCase); |
| | | 359 | | // ② Working directory/root |
| | 636 | 360 | | SetWorkingDirectoryIfNeeded(kestrunRoot); |
| | | 361 | | |
| | | 362 | | // ③ Ensure Kestrun module path is available |
| | 636 | 363 | | AddKestrunModulePathIfMissing(modulePathsObj); |
| | | 364 | | |
| | | 365 | | // ④ WebApplicationBuilder |
| | | 366 | | // NOTE: |
| | | 367 | | // ASP.NET Core's WebApplicationBuilder validates that ContentRootPath exists. |
| | | 368 | | // On Unix/macOS, the process current working directory (CWD) can be deleted by tests or external code. |
| | | 369 | | // If we derive ContentRootPath from a missing/deleted directory, CreateBuilder throws. |
| | | 370 | | // We therefore (a) choose an existing directory when possible and (b) retry with a stable fallback |
| | | 371 | | // to keep host creation resilient in CI where test ordering/parallelism can surface this. |
| | | 372 | | WebApplicationOptions CreateWebAppOptions(string contentRootPath) |
| | | 373 | | { |
| | 636 | 374 | | return new() |
| | 636 | 375 | | { |
| | 636 | 376 | | ContentRootPath = contentRootPath, |
| | 636 | 377 | | Args = args ?? [], |
| | 636 | 378 | | EnvironmentName = EnvironmentHelper.Name |
| | 636 | 379 | | }; |
| | | 380 | | } |
| | | 381 | | |
| | 636 | 382 | | var contentRootPath = GetSafeContentRootPath(kestrunRoot); |
| | | 383 | | |
| | | 384 | | try |
| | | 385 | | { |
| | 636 | 386 | | Builder = WebApplication.CreateBuilder(CreateWebAppOptions(contentRootPath)); |
| | 636 | 387 | | } |
| | 0 | 388 | | catch (ArgumentException ex) when ( |
| | 0 | 389 | | string.Equals(ex.ParamName, "contentRootPath", StringComparison.OrdinalIgnoreCase) && |
| | 0 | 390 | | !string.Equals(contentRootPath, AppContext.BaseDirectory, StringComparison.Ordinal)) |
| | | 391 | | { |
| | | 392 | | // The selected content root may have been deleted between resolution and builder initialization |
| | | 393 | | // (TOCTOU race) or the process CWD may have become invalid. Fall back to a stable path so host |
| | | 394 | | // creation does not fail. |
| | 0 | 395 | | Builder = WebApplication.CreateBuilder(CreateWebAppOptions(AppContext.BaseDirectory)); |
| | 0 | 396 | | } |
| | | 397 | | // ✅ add here, after Builder is definitely assigned |
| | 636 | 398 | | _ = Builder.Services.Configure<HostOptions>(o => |
| | 636 | 399 | | { |
| | 110 | 400 | | _ = o.ShutdownTimeout = TimeSpan.FromSeconds(5); |
| | 746 | 401 | | }); |
| | | 402 | | |
| | | 403 | | // Enable Serilog for the host |
| | 636 | 404 | | _ = Builder.Host.UseSerilog(); |
| | | 405 | | |
| | | 406 | | // Make this KestrunHost available via DI so framework-created components (e.g., auth handlers) |
| | | 407 | | // can resolve it. We register the current instance as a singleton. |
| | 636 | 408 | | _ = Builder.Services.AddSingleton(this); |
| | | 409 | | |
| | | 410 | | // Expose Serilog.ILogger via DI for components (e.g., SignalR hubs) that depend on Serilog's logger |
| | | 411 | | // ASP.NET Core registers Microsoft.Extensions.Logging.ILogger by default; we also bind Serilog.ILogger |
| | | 412 | | // to the same instance so constructors like `KestrunHub(Serilog.ILogger logger)` resolve properly. |
| | 636 | 413 | | _ = Builder.Services.AddSingleton(Logger); |
| | | 414 | | |
| | | 415 | | // ⑤ Options |
| | 636 | 416 | | InitializeOptions(appName); |
| | | 417 | | |
| | | 418 | | // ⑥ Add user-provided module paths |
| | 636 | 419 | | AddUserModulePaths(modulePathsObj); |
| | | 420 | | |
| | 636 | 421 | | Logger.Information("Current working directory: {CurrentDirectory}", GetSafeCurrentDirectory()); |
| | 636 | 422 | | } |
| | | 423 | | #endregion |
| | | 424 | | |
| | | 425 | | #region Helpers |
| | | 426 | | |
| | | 427 | | /// <summary> |
| | | 428 | | /// Adds a form parsing option for the specified name. |
| | | 429 | | /// </summary> |
| | | 430 | | /// <param name="options">The form options to add.</param> |
| | | 431 | | /// <returns>True if the option was added successfully; otherwise, false.</returns> |
| | | 432 | | public bool AddFormOption(KrFormOptions options) |
| | | 433 | | { |
| | 5 | 434 | | ArgumentNullException.ThrowIfNull(options); |
| | 5 | 435 | | ArgumentNullException.ThrowIfNull(options.Name); |
| | | 436 | | |
| | 5 | 437 | | if (Runtime.FormOptions.TryAdd(options.Name, options)) |
| | | 438 | | { |
| | | 439 | | // Link scoped rules under their container rule(s) once at configuration-time. |
| | | 440 | | // This keeps KrFormPartRule.NestedRules useful for introspection/debugging. |
| | 5 | 441 | | FormHelper.PopulateNestedRulesFromScopes(options); |
| | | 442 | | |
| | 5 | 443 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 444 | | { |
| | 5 | 445 | | Logger.Debug("Added form option with name '{FormOptionName}'.", options.Name); |
| | | 446 | | } |
| | 5 | 447 | | return true; |
| | | 448 | | } |
| | | 449 | | else |
| | | 450 | | { |
| | 0 | 451 | | if (Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 452 | | { |
| | 0 | 453 | | Logger.Warning("Form option with name '{FormOptionName}' already exists. Skipping addition.", options.Na |
| | | 454 | | } |
| | 0 | 455 | | return false; |
| | | 456 | | } |
| | | 457 | | } |
| | | 458 | | |
| | | 459 | | /// <summary> |
| | | 460 | | /// Gets the form parsing option for the specified name. |
| | | 461 | | /// </summary> |
| | | 462 | | /// <param name="name">The name of the form option.</param> |
| | | 463 | | /// <returns>The form options if found; otherwise, null.</returns> |
| | 1 | 464 | | public KrFormOptions? GetFormOption(string name) => Runtime.FormOptions.TryGetValue(name, out var options) ? options |
| | | 465 | | |
| | | 466 | | /// <summary> |
| | | 467 | | /// Adds a form part rule for the specified name. |
| | | 468 | | /// </summary> |
| | | 469 | | /// <param name="ruleOptions">The form part rule to add.</param> |
| | | 470 | | /// <returns>True if the rule was added successfully; otherwise, false.</returns> |
| | | 471 | | public bool AddFormPartRule(KrFormPartRule ruleOptions) |
| | | 472 | | { |
| | 34 | 473 | | ArgumentNullException.ThrowIfNull(ruleOptions); |
| | 34 | 474 | | ArgumentNullException.ThrowIfNull(ruleOptions.Name); |
| | | 475 | | |
| | 34 | 476 | | if (Runtime.FormPartRules.TryAdd(ruleOptions.Name, ruleOptions)) |
| | | 477 | | { |
| | 22 | 478 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 479 | | { |
| | 22 | 480 | | Logger.Debug("Added form part rule with name '{FormPartRuleName}'.", ruleOptions.Name); |
| | | 481 | | } |
| | 22 | 482 | | return true; |
| | | 483 | | } |
| | | 484 | | else |
| | | 485 | | { |
| | 12 | 486 | | if (Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 487 | | { |
| | 12 | 488 | | Logger.Warning("Form part rule with name '{FormPartRuleName}' already exists. Skipping addition.", ruleO |
| | | 489 | | } |
| | 12 | 490 | | return false; |
| | | 491 | | } |
| | | 492 | | } |
| | | 493 | | |
| | | 494 | | /// <summary> |
| | | 495 | | /// Gets the form part rule for the specified name. |
| | | 496 | | /// </summary> |
| | | 497 | | /// <param name="name">The name of the form part rule.</param> |
| | | 498 | | /// <returns>The form part rule if found; otherwise, null.</returns> |
| | 0 | 499 | | public KrFormPartRule? GetFormPartRule(string name) => Runtime.FormPartRules.TryGetValue(name, out var options) ? op |
| | | 500 | | |
| | | 501 | | /// <summary> |
| | | 502 | | /// Gets the OpenAPI document descriptor for the specified document ID. |
| | | 503 | | /// </summary> |
| | | 504 | | /// <param name="apiDocId">The ID of the OpenAPI document.</param> |
| | | 505 | | /// <returns>The OpenAPI document descriptor.</returns> |
| | | 506 | | public OpenApiDocDescriptor GetOrCreateOpenApiDocument(string apiDocId) |
| | | 507 | | { |
| | 28 | 508 | | if (string.IsNullOrWhiteSpace(apiDocId)) |
| | | 509 | | { |
| | 0 | 510 | | throw new ArgumentException("Document ID cannot be null or whitespace.", nameof(apiDocId)); |
| | | 511 | | } |
| | | 512 | | // Check if descriptor already exists |
| | 28 | 513 | | if (OpenApiDocumentDescriptor.TryGetValue(apiDocId, out var descriptor)) |
| | | 514 | | { |
| | 5 | 515 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 516 | | { |
| | 5 | 517 | | Logger.Debug("OpenAPI document descriptor for ID '{DocId}' already exists. Returning existing descriptor |
| | | 518 | | } |
| | | 519 | | } |
| | | 520 | | else |
| | | 521 | | { |
| | 23 | 522 | | descriptor = new OpenApiDocDescriptor(this, apiDocId); |
| | 23 | 523 | | OpenApiDocumentDescriptor[apiDocId] = descriptor; |
| | | 524 | | } |
| | 28 | 525 | | return descriptor; |
| | | 526 | | } |
| | | 527 | | |
| | | 528 | | /// <summary> |
| | | 529 | | /// Gets the list of OpenAPI document descriptors for the specified document IDs. |
| | | 530 | | /// </summary> |
| | | 531 | | /// <param name="openApiDocIds"> The array of OpenAPI document IDs.</param> |
| | | 532 | | /// <returns>A list of OpenApiDocDescriptor objects corresponding to the provided document IDs.</returns> |
| | | 533 | | public List<OpenApiDocDescriptor> GetOrCreateOpenApiDocument(string[] openApiDocIds) |
| | | 534 | | { |
| | 2 | 535 | | var list = new List<OpenApiDocDescriptor>(); |
| | 8 | 536 | | foreach (var apiDocId in openApiDocIds) |
| | | 537 | | { |
| | 2 | 538 | | list.Add(GetOrCreateOpenApiDocument(apiDocId)); |
| | | 539 | | } |
| | 2 | 540 | | return list; |
| | | 541 | | } |
| | | 542 | | |
| | | 543 | | /// <summary> |
| | | 544 | | /// Logs constructor arguments at Debug level for diagnostics. |
| | | 545 | | /// </summary> |
| | | 546 | | private void LogConstructorArgs(string? appName, bool defaultLogger, string? kestrunRoot, int modulePathsLength) |
| | | 547 | | { |
| | 636 | 548 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 549 | | { |
| | 464 | 550 | | Logger.Debug( |
| | 464 | 551 | | "KestrunHost ctor: AppName={AppName}, DefaultLogger={DefaultLogger}, KestrunRoot={KestrunRoot}, ModulePa |
| | 464 | 552 | | appName, defaultLogger, kestrunRoot, modulePathsLength); |
| | | 553 | | } |
| | 636 | 554 | | } |
| | | 555 | | |
| | | 556 | | /// <summary> |
| | | 557 | | /// Sets the current working directory to the provided Kestrun root if needed and stores it. |
| | | 558 | | /// </summary> |
| | | 559 | | /// <param name="kestrunRoot">The Kestrun root directory path.</param> |
| | | 560 | | private void SetWorkingDirectoryIfNeeded(string? kestrunRoot) |
| | | 561 | | { |
| | 636 | 562 | | if (string.IsNullOrWhiteSpace(kestrunRoot)) |
| | | 563 | | { |
| | 488 | 564 | | return; |
| | | 565 | | } |
| | | 566 | | |
| | 148 | 567 | | if (!string.Equals(GetSafeCurrentDirectory(), kestrunRoot, StringComparison.Ordinal)) |
| | | 568 | | { |
| | 111 | 569 | | Directory.SetCurrentDirectory(kestrunRoot); |
| | 111 | 570 | | Logger.Information("Changed current directory to Kestrun root: {KestrunRoot}", kestrunRoot); |
| | | 571 | | } |
| | | 572 | | else |
| | | 573 | | { |
| | 37 | 574 | | Logger.Verbose("Current directory is already set to Kestrun root: {KestrunRoot}", kestrunRoot); |
| | | 575 | | } |
| | | 576 | | |
| | 148 | 577 | | KestrunRoot = kestrunRoot; |
| | 148 | 578 | | } |
| | | 579 | | |
| | | 580 | | private static string GetSafeContentRootPath(string? kestrunRoot) |
| | | 581 | | { |
| | 636 | 582 | | var candidate = !string.IsNullOrWhiteSpace(kestrunRoot) |
| | 636 | 583 | | ? kestrunRoot |
| | 636 | 584 | | : GetSafeCurrentDirectory(); |
| | | 585 | | |
| | | 586 | | // WebApplication.CreateBuilder requires that ContentRootPath exists. |
| | | 587 | | // On Unix/macOS, getcwd() can fail (or return a path that was deleted) if the CWD was removed. |
| | | 588 | | // This can happen in tests that use temp directories and delete them after constructing a host. |
| | | 589 | | // Guard here to avoid injecting a non-existent content root into ASP.NET Core. |
| | 636 | 590 | | return Directory.Exists(candidate) |
| | 636 | 591 | | ? candidate |
| | 636 | 592 | | : AppContext.BaseDirectory; |
| | | 593 | | } |
| | | 594 | | |
| | | 595 | | private static string GetSafeCurrentDirectory() |
| | | 596 | | { |
| | | 597 | | try |
| | | 598 | | { |
| | 1382 | 599 | | return Directory.GetCurrentDirectory(); |
| | | 600 | | } |
| | 2 | 601 | | catch (Exception ex) when ( |
| | 2 | 602 | | ex is IOException or |
| | 2 | 603 | | UnauthorizedAccessException or |
| | 2 | 604 | | DirectoryNotFoundException or |
| | 2 | 605 | | FileNotFoundException) |
| | | 606 | | { |
| | | 607 | | // On Unix/macOS, getcwd() can fail with ENOENT if the CWD was deleted. |
| | | 608 | | // Fall back to the app base directory to keep host creation resilient. |
| | 2 | 609 | | return AppContext.BaseDirectory; |
| | | 610 | | } |
| | 1382 | 611 | | } |
| | | 612 | | |
| | | 613 | | /// <summary> |
| | | 614 | | /// Ensures the core Kestrun module path is present; if missing, locates and adds it. |
| | | 615 | | /// </summary> |
| | | 616 | | /// <param name="modulePathsObj">The array of module paths to check.</param> |
| | | 617 | | private void AddKestrunModulePathIfMissing(string[]? modulePathsObj) |
| | | 618 | | { |
| | 636 | 619 | | var needsLocate = modulePathsObj is null || |
| | 673 | 620 | | (modulePathsObj?.Any(p => p.Contains("Kestrun.psm1", StringComparison.Ordinal)) == false); |
| | 636 | 621 | | if (!needsLocate) |
| | | 622 | | { |
| | 37 | 623 | | return; |
| | | 624 | | } |
| | | 625 | | |
| | 599 | 626 | | var kestrunModulePath = PowerShellModuleLocator.LocateKestrunModule(); |
| | 599 | 627 | | if (string.IsNullOrWhiteSpace(kestrunModulePath)) |
| | | 628 | | { |
| | 0 | 629 | | Logger.Fatal("Kestrun module not found. Ensure the Kestrun module is installed."); |
| | 0 | 630 | | throw new FileNotFoundException("Kestrun module not found."); |
| | | 631 | | } |
| | | 632 | | |
| | 599 | 633 | | Logger.Information("Found Kestrun module at: {KestrunModulePath}", kestrunModulePath); |
| | 599 | 634 | | Logger.Verbose("Adding Kestrun module path: {KestrunModulePath}", kestrunModulePath); |
| | 599 | 635 | | _modulePaths.Add(kestrunModulePath); |
| | 599 | 636 | | } |
| | | 637 | | |
| | | 638 | | /// <summary> |
| | | 639 | | /// Initializes Kestrun options and sets the application name when provided. |
| | | 640 | | /// </summary> |
| | | 641 | | /// <param name="appName">The name of the application.</param> |
| | | 642 | | private void InitializeOptions(string? appName) |
| | | 643 | | { |
| | 636 | 644 | | if (string.IsNullOrEmpty(appName)) |
| | | 645 | | { |
| | 1 | 646 | | Logger.Information("No application name provided, using default."); |
| | 1 | 647 | | Options = new KestrunOptions(); |
| | | 648 | | } |
| | | 649 | | else |
| | | 650 | | { |
| | 635 | 651 | | Logger.Information("Setting application name: {AppName}", appName); |
| | 635 | 652 | | Options = new KestrunOptions { ApplicationName = appName }; |
| | | 653 | | } |
| | 635 | 654 | | } |
| | | 655 | | |
| | | 656 | | /// <summary> |
| | | 657 | | /// Adds user-provided module paths if they exist, logging warnings for invalid entries. |
| | | 658 | | /// </summary> |
| | | 659 | | /// <param name="modulePathsObj">The array of module paths to check.</param> |
| | | 660 | | private void AddUserModulePaths(string[]? modulePathsObj) |
| | | 661 | | { |
| | 636 | 662 | | if (modulePathsObj is IEnumerable<object> modulePathsEnum) |
| | | 663 | | { |
| | 148 | 664 | | foreach (var modPathObj in modulePathsEnum) |
| | | 665 | | { |
| | 37 | 666 | | if (modPathObj is string modPath && !string.IsNullOrWhiteSpace(modPath)) |
| | | 667 | | { |
| | 37 | 668 | | if (File.Exists(modPath)) |
| | | 669 | | { |
| | 37 | 670 | | Logger.Information("[KestrunHost] Adding module path: {ModPath}", modPath); |
| | 37 | 671 | | _modulePaths.Add(modPath); |
| | | 672 | | } |
| | | 673 | | else |
| | | 674 | | { |
| | 0 | 675 | | Logger.Warning("[KestrunHost] Module path does not exist: {ModPath}", modPath); |
| | | 676 | | } |
| | | 677 | | } |
| | | 678 | | else |
| | | 679 | | { |
| | 0 | 680 | | Logger.Warning("[KestrunHost] Invalid module path provided."); |
| | | 681 | | } |
| | | 682 | | } |
| | | 683 | | } |
| | 636 | 684 | | } |
| | | 685 | | #endregion |
| | | 686 | | |
| | | 687 | | #region Health Probes |
| | | 688 | | |
| | | 689 | | /// <summary> |
| | | 690 | | /// Registers the provided <see cref="IProbe"/> instance with the host. |
| | | 691 | | /// </summary> |
| | | 692 | | /// <param name="probe">The probe to register.</param> |
| | | 693 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 694 | | public KestrunHost AddProbe(IProbe probe) |
| | | 695 | | { |
| | 0 | 696 | | ArgumentNullException.ThrowIfNull(probe); |
| | 0 | 697 | | RegisterProbeInternal(probe); |
| | 0 | 698 | | return this; |
| | | 699 | | } |
| | | 700 | | |
| | | 701 | | /// <summary> |
| | | 702 | | /// Registers a delegate-based probe. |
| | | 703 | | /// </summary> |
| | | 704 | | /// <param name="name">Probe name.</param> |
| | | 705 | | /// <param name="tags">Optional tag list used for filtering.</param> |
| | | 706 | | /// <param name="callback">Delegate executed when the probe runs.</param> |
| | | 707 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 708 | | public KestrunHost AddProbe(string name, string[]? tags, Func<CancellationToken, Task<ProbeResult>> callback) |
| | | 709 | | { |
| | 0 | 710 | | ArgumentException.ThrowIfNullOrEmpty(name); |
| | 0 | 711 | | ArgumentNullException.ThrowIfNull(callback); |
| | | 712 | | |
| | 0 | 713 | | var probe = new DelegateProbe(name, tags, callback); |
| | 0 | 714 | | RegisterProbeInternal(probe); |
| | 0 | 715 | | return this; |
| | | 716 | | } |
| | | 717 | | |
| | | 718 | | /// <summary> |
| | | 719 | | /// Registers a script-based probe written in any supported language. |
| | | 720 | | /// </summary> |
| | | 721 | | /// <param name="name">Probe name.</param> |
| | | 722 | | /// <param name="tags">Optional tag list used for filtering.</param> |
| | | 723 | | /// <param name="code">Script contents.</param> |
| | | 724 | | /// <param name="language">Optional language override. When null, <see cref="KestrunOptions.Health"/> defaults are u |
| | | 725 | | /// <param name="arguments">Optional argument dictionary exposed to the script.</param> |
| | | 726 | | /// <param name="extraImports">Optional language-specific imports.</param> |
| | | 727 | | /// <param name="extraRefs">Optional additional assembly references.</param> |
| | | 728 | | /// <returns>The current <see cref="KestrunHost"/> instance.</returns> |
| | | 729 | | public KestrunHost AddProbe( |
| | | 730 | | string name, |
| | | 731 | | string[]? tags, |
| | | 732 | | string code, |
| | | 733 | | ScriptLanguage? language = null, |
| | | 734 | | IReadOnlyDictionary<string, object?>? arguments = null, |
| | | 735 | | string[]? extraImports = null, |
| | | 736 | | Assembly[]? extraRefs = null) |
| | | 737 | | { |
| | 0 | 738 | | ArgumentException.ThrowIfNullOrEmpty(name); |
| | 0 | 739 | | ArgumentException.ThrowIfNullOrEmpty(code); |
| | | 740 | | |
| | 0 | 741 | | var effectiveLanguage = language ?? Options.Health.DefaultScriptLanguage; |
| | 0 | 742 | | var logger = Logger.ForContext("HealthProbe", name); |
| | 0 | 743 | | var probe = ScriptProbeFactory.Create(host: this, name: name, tags: tags, |
| | 0 | 744 | | effectiveLanguage, code: code, |
| | 0 | 745 | | runspaceAccessor: effectiveLanguage == ScriptLanguage.PowerShell ? () => RunspacePool : null, |
| | 0 | 746 | | arguments: arguments, extraImports: extraImports, extraRefs: extraRefs); |
| | | 747 | | |
| | 0 | 748 | | RegisterProbeInternal(probe); |
| | 0 | 749 | | return this; |
| | | 750 | | } |
| | | 751 | | |
| | | 752 | | /// <summary> |
| | | 753 | | /// Returns a snapshot of the currently registered probes. |
| | | 754 | | /// </summary> |
| | | 755 | | internal IReadOnlyList<IProbe> GetHealthProbesSnapshot() |
| | | 756 | | { |
| | 0 | 757 | | lock (_healthProbeLock) |
| | | 758 | | { |
| | 0 | 759 | | return [.. HealthProbes]; |
| | | 760 | | } |
| | 0 | 761 | | } |
| | | 762 | | |
| | | 763 | | private void RegisterProbeInternal(IProbe probe) |
| | | 764 | | { |
| | 60 | 765 | | lock (_healthProbeLock) |
| | | 766 | | { |
| | 60 | 767 | | var index = HealthProbes.FindIndex(p => string.Equals(p.Name, probe.Name, StringComparison.OrdinalIgnoreCase |
| | 60 | 768 | | if (index >= 0) |
| | | 769 | | { |
| | 0 | 770 | | HealthProbes[index] = probe; |
| | 0 | 771 | | Logger.Information("Replaced health probe {ProbeName}.", probe.Name); |
| | | 772 | | } |
| | | 773 | | else |
| | | 774 | | { |
| | 60 | 775 | | HealthProbes.Add(probe); |
| | 60 | 776 | | Logger.Information("Registered health probe {ProbeName}.", probe.Name); |
| | | 777 | | } |
| | 60 | 778 | | } |
| | 60 | 779 | | } |
| | | 780 | | |
| | | 781 | | #endregion |
| | | 782 | | #region OpenAPI |
| | | 783 | | |
| | | 784 | | /// <summary> |
| | | 785 | | /// Adds callback automation middleware to the Kestrun host. |
| | | 786 | | /// </summary> |
| | | 787 | | /// <param name="options">Optional callback dispatch options.</param> |
| | | 788 | | /// <returns>The updated Kestrun host.</returns> |
| | | 789 | | public KestrunHost AddCallbacksAutomation(CallbackDispatchOptions? options = null) |
| | | 790 | | { |
| | 0 | 791 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 792 | | { |
| | 0 | 793 | | Logger.Debug( |
| | 0 | 794 | | "Adding callback automation middleware (custom configuration supplied: {HasConfig})", |
| | 0 | 795 | | options != null); |
| | | 796 | | } |
| | 0 | 797 | | options ??= new CallbackDispatchOptions(); |
| | 0 | 798 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 799 | | { |
| | 0 | 800 | | Logger.Debug("Adding callback automation middleware with options: {@Options}", options); |
| | | 801 | | } |
| | | 802 | | |
| | 0 | 803 | | _ = AddService(services => |
| | 0 | 804 | | { |
| | 0 | 805 | | _ = services.AddSingleton(options ?? new CallbackDispatchOptions()); |
| | 0 | 806 | | _ = services.AddSingleton<InMemoryCallbackQueue>(); |
| | 0 | 807 | | _ = services.AddSingleton<ICallbackDispatcher, InMemoryCallbackDispatcher>(); |
| | 0 | 808 | | _ = services.AddHostedService<InMemoryCallbackDispatchWorker>(); |
| | 0 | 809 | | _ = services.AddHttpClient("kestrun-callbacks", c => |
| | 0 | 810 | | { |
| | 0 | 811 | | c.Timeout = options?.DefaultTimeout ?? TimeSpan.FromSeconds(30); |
| | 0 | 812 | | }); |
| | 0 | 813 | | _ = services.AddSingleton<ICallbackRetryPolicy>(sp => |
| | 0 | 814 | | { |
| | 0 | 815 | | return new DefaultCallbackRetryPolicy(options); |
| | 0 | 816 | | }); |
| | 0 | 817 | | |
| | 0 | 818 | | _ = services.AddSingleton<ICallbackUrlResolver, DefaultCallbackUrlResolver>(); |
| | 0 | 819 | | _ = services.AddSingleton<ICallbackBodySerializer, JsonCallbackBodySerializer>(); |
| | 0 | 820 | | |
| | 0 | 821 | | _ = services.AddHttpClient<ICallbackSender, HttpCallbackSender>(); |
| | 0 | 822 | | |
| | 0 | 823 | | _ = services.AddHostedService<CallbackWorker>(); |
| | 0 | 824 | | }); |
| | 0 | 825 | | return this; |
| | | 826 | | } |
| | | 827 | | #endregion |
| | | 828 | | #region ListenerOptions |
| | | 829 | | |
| | | 830 | | /// <summary> |
| | | 831 | | /// Configures a listener for the Kestrun host with the specified port, optional IP address, certificate, protocols, |
| | | 832 | | /// </summary> |
| | | 833 | | /// <param name="port">The port number to listen on.</param> |
| | | 834 | | /// <param name="ipAddress">The IP address to bind to. If null, binds to any address.</param> |
| | | 835 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 836 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 837 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 838 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 839 | | public KestrunHost ConfigureListener( |
| | | 840 | | int port, |
| | | 841 | | IPAddress? ipAddress = null, |
| | | 842 | | X509Certificate2? x509Certificate = null, |
| | | 843 | | HttpProtocols protocols = HttpProtocols.Http1, |
| | | 844 | | bool useConnectionLogging = false) |
| | | 845 | | { |
| | 41 | 846 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 847 | | { |
| | 18 | 848 | | Logger.Debug("ConfigureListener port={Port}, ipAddress={IPAddress}, protocols={Protocols}, useConnectionLogg |
| | | 849 | | } |
| | | 850 | | // Validate state |
| | 41 | 851 | | if (IsConfigured) |
| | | 852 | | { |
| | 0 | 853 | | throw new InvalidOperationException("Cannot configure listeners after configuration is applied."); |
| | | 854 | | } |
| | | 855 | | // Validate protocols |
| | 41 | 856 | | if (protocols == HttpProtocols.Http1AndHttp2AndHttp3 && !IsQuicSupported()) |
| | | 857 | | { |
| | 4 | 858 | | Logger.Warning("HTTP/3 cannot be enabled because QUIC/libmsquic is not available on this platform. Falling b |
| | | 859 | | |
| | 4 | 860 | | protocols = HttpProtocols.Http1AndHttp2; |
| | | 861 | | } |
| | | 862 | | // Resolve dynamic port when requested |
| | 41 | 863 | | if (port == 0) |
| | | 864 | | { |
| | 23 | 865 | | var bindAddress = ipAddress ?? IPAddress.Any; |
| | 23 | 866 | | port = ResolveEphemeralPort(bindAddress); |
| | 23 | 867 | | Logger.Information("Selected ephemeral port {Port} for listener on {Address}", port, bindAddress); |
| | | 868 | | } |
| | | 869 | | // Add listener |
| | 41 | 870 | | Options.Listeners.Add(new ListenerOptions |
| | 41 | 871 | | { |
| | 41 | 872 | | IPAddress = ipAddress ?? IPAddress.Any, |
| | 41 | 873 | | Port = port, |
| | 41 | 874 | | UseHttps = x509Certificate != null, |
| | 41 | 875 | | X509Certificate = x509Certificate, |
| | 41 | 876 | | Protocols = protocols, |
| | 41 | 877 | | UseConnectionLogging = useConnectionLogging |
| | 41 | 878 | | }); |
| | 41 | 879 | | return this; |
| | | 880 | | } |
| | | 881 | | |
| | | 882 | | /// <summary> |
| | | 883 | | /// Configures a listener for the Kestrun host with the specified port, optional IP address, and connection logging. |
| | | 884 | | /// </summary> |
| | | 885 | | /// <param name="port">The port number to listen on.</param> |
| | | 886 | | /// <param name="ipAddress">The IP address to bind to. If null, binds to any address.</param> |
| | | 887 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 888 | | public void ConfigureListener( |
| | | 889 | | int port, |
| | | 890 | | IPAddress? ipAddress = null, |
| | 24 | 891 | | bool useConnectionLogging = false) => _ = ConfigureListener(port: port, ipAddress: ipAddress, x509Certificate: null, |
| | | 892 | | |
| | | 893 | | /// <summary> |
| | | 894 | | /// Configures a listener for the Kestrun host with the specified port and connection logging option. |
| | | 895 | | /// </summary> |
| | | 896 | | /// <param name="port">The port number to listen on.</param> |
| | | 897 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 898 | | public void ConfigureListener( |
| | | 899 | | int port, |
| | 1 | 900 | | bool useConnectionLogging = false) => _ = ConfigureListener(port: port, ipAddress: null, x509Certificate: null, prot |
| | | 901 | | |
| | | 902 | | /// <summary> |
| | | 903 | | /// Configures listeners for the Kestrun host by resolving the specified host name to IP addresses and binding to ea |
| | | 904 | | /// </summary> |
| | | 905 | | /// <param name="hostName">The host name to resolve and bind to.</param> |
| | | 906 | | /// <param name="port">The port number to listen on.</param> |
| | | 907 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 908 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 909 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 910 | | /// <param name="families">Optional array of address families to filter resolved addresses (e.g., IPv4-only).</param |
| | | 911 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 912 | | /// <exception cref="ArgumentException">Thrown when the host name is null or whitespace.</exception> |
| | | 913 | | /// <exception cref="InvalidOperationException">Thrown when no valid IP addresses are resolved.</exception> |
| | | 914 | | public KestrunHost ConfigureListener( |
| | | 915 | | string hostName, |
| | | 916 | | int port, |
| | | 917 | | X509Certificate2? x509Certificate = null, |
| | | 918 | | HttpProtocols protocols = HttpProtocols.Http1, |
| | | 919 | | bool useConnectionLogging = false, |
| | | 920 | | AddressFamily[]? families = null) // e.g. new[] { AddressFamily.InterNetwork } for IPv4-only |
| | | 921 | | { |
| | 0 | 922 | | if (string.IsNullOrWhiteSpace(hostName)) |
| | | 923 | | { |
| | 0 | 924 | | throw new ArgumentException("Host name must be provided.", nameof(hostName)); |
| | | 925 | | } |
| | | 926 | | |
| | | 927 | | // If caller passed an IP literal, just bind once. |
| | 0 | 928 | | if (IPAddress.TryParse(hostName, out var parsedIp)) |
| | | 929 | | { |
| | 0 | 930 | | _ = ConfigureListener(port, parsedIp, x509Certificate, protocols, useConnectionLogging); |
| | 0 | 931 | | return this; |
| | | 932 | | } |
| | | 933 | | |
| | | 934 | | // Resolve and bind to ALL matching addresses (IPv4/IPv6) |
| | 0 | 935 | | var addrs = Dns.GetHostAddresses(hostName) |
| | 0 | 936 | | .Where(a => families is null || families.Length == 0 || families.Contains(a.AddressFamily)) |
| | 0 | 937 | | .Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6) |
| | 0 | 938 | | .ToArray(); |
| | | 939 | | |
| | 0 | 940 | | if (addrs.Length == 0) |
| | | 941 | | { |
| | 0 | 942 | | throw new InvalidOperationException($"No IPv4/IPv6 addresses resolved for host '{hostName}'."); |
| | | 943 | | } |
| | | 944 | | |
| | 0 | 945 | | foreach (var addr in addrs) |
| | | 946 | | { |
| | 0 | 947 | | _ = ConfigureListener(port, addr, x509Certificate, protocols, useConnectionLogging); |
| | | 948 | | } |
| | | 949 | | |
| | 0 | 950 | | return this; |
| | | 951 | | } |
| | | 952 | | |
| | | 953 | | /// <summary> |
| | | 954 | | /// Configures listeners for the Kestrun host based on the provided absolute URI, resolving the host to IP addresses |
| | | 955 | | /// </summary> |
| | | 956 | | /// <param name="uri">The absolute URI to configure the listener for.</param> |
| | | 957 | | /// <param name="x509Certificate">The X509 certificate for HTTPS. If null, HTTPS is not used.</param> |
| | | 958 | | /// <param name="protocols">The HTTP protocols to use.</param> |
| | | 959 | | /// <param name="useConnectionLogging">Specifies whether to enable connection logging.</param> |
| | | 960 | | /// <param name="families">Optional array of address families to filter resolved addresses (e.g., IPv4-only).</param |
| | | 961 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 962 | | /// <exception cref="ArgumentException">Thrown when the provided URI is not absolute.</exception> |
| | | 963 | | /// <exception cref="InvalidOperationException">Thrown when no valid IP addresses are resolved.</exception> |
| | | 964 | | public KestrunHost ConfigureListener( |
| | | 965 | | Uri uri, |
| | | 966 | | X509Certificate2? x509Certificate = null, |
| | | 967 | | HttpProtocols? protocols = null, |
| | | 968 | | bool useConnectionLogging = false, |
| | | 969 | | AddressFamily[]? families = null) |
| | | 970 | | { |
| | 0 | 971 | | ArgumentNullException.ThrowIfNull(uri); |
| | | 972 | | |
| | 0 | 973 | | if (!uri.IsAbsoluteUri) |
| | | 974 | | { |
| | 0 | 975 | | throw new ArgumentException("URL must be absolute.", nameof(uri)); |
| | | 976 | | } |
| | | 977 | | |
| | 0 | 978 | | var isHttps = uri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase); |
| | 0 | 979 | | var port = uri.IsDefaultPort ? (isHttps ? 443 : 80) : uri.Port; |
| | | 980 | | |
| | | 981 | | // Default: HTTPS → H1+H2, HTTP → H1 |
| | 0 | 982 | | var chosenProtocols = protocols ?? (isHttps ? HttpProtocols.Http1AndHttp2 : HttpProtocols.Http1); |
| | | 983 | | |
| | | 984 | | // Delegate to hostname overload (which will resolve or handle IP literal) |
| | 0 | 985 | | return ConfigureListener( |
| | 0 | 986 | | hostName: uri.Host, |
| | 0 | 987 | | port: port, |
| | 0 | 988 | | x509Certificate: x509Certificate, |
| | 0 | 989 | | protocols: chosenProtocols, |
| | 0 | 990 | | useConnectionLogging: useConnectionLogging, |
| | 0 | 991 | | families: families |
| | 0 | 992 | | ); |
| | | 993 | | } |
| | | 994 | | |
| | | 995 | | #endregion |
| | | 996 | | |
| | | 997 | | #region Configuration |
| | | 998 | | |
| | | 999 | | /// <summary> |
| | | 1000 | | /// Validates if configuration can be applied and returns early if already configured. |
| | | 1001 | | /// </summary> |
| | | 1002 | | /// <returns>True if configuration should proceed, false if it should be skipped.</returns> |
| | | 1003 | | internal bool ValidateConfiguration() |
| | | 1004 | | { |
| | 84 | 1005 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1006 | | { |
| | 41 | 1007 | | Logger.Debug("EnableConfiguration(options) called"); |
| | | 1008 | | } |
| | | 1009 | | |
| | 84 | 1010 | | if (IsConfigured) |
| | | 1011 | | { |
| | 22 | 1012 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1013 | | { |
| | 2 | 1014 | | Logger.Debug("Configuration already applied, skipping"); |
| | | 1015 | | } |
| | 22 | 1016 | | return false; // Already configured |
| | | 1017 | | } |
| | | 1018 | | |
| | 62 | 1019 | | return true; |
| | | 1020 | | } |
| | | 1021 | | |
| | | 1022 | | /// <summary> |
| | | 1023 | | /// Creates and initializes the runspace pool for PowerShell execution. |
| | | 1024 | | /// </summary> |
| | | 1025 | | /// <param name="userVariables">User-defined variables to inject into the runspace pool.</param> |
| | | 1026 | | /// <param name="userFunctions">User-defined functions to inject into the runspace pool.</param> |
| | | 1027 | | /// <param name="openApiClassesPath">Path to the OpenAPI class definitions to inject into the runspace pool.</param> |
| | | 1028 | | /// <exception cref="InvalidOperationException">Thrown when runspace pool creation fails.</exception> |
| | | 1029 | | internal void InitializeRunspacePool(Dictionary<string, object>? userVariables, Dictionary<string, string>? userFunc |
| | | 1030 | | { |
| | 63 | 1031 | | _runspacePool = |
| | 63 | 1032 | | CreateRunspacePool(Options.MaxRunspaces, userVariables, userFunctions, openApiClassesPath) ?? |
| | 63 | 1033 | | throw new InvalidOperationException("Failed to create runspace pool."); |
| | 63 | 1034 | | if (Logger.IsEnabled(LogEventLevel.Verbose)) |
| | | 1035 | | { |
| | 0 | 1036 | | Logger.Verbose("Runspace pool created with max runspaces: {MaxRunspaces}", Options.MaxRunspaces); |
| | | 1037 | | } |
| | 63 | 1038 | | } |
| | | 1039 | | |
| | | 1040 | | /// <summary> |
| | | 1041 | | /// Configures the Kestrel web server with basic options. |
| | | 1042 | | /// </summary> |
| | | 1043 | | internal void ConfigureKestrelBase() |
| | | 1044 | | { |
| | 61 | 1045 | | _ = Builder.WebHost.UseKestrel(opts => |
| | 61 | 1046 | | { |
| | 60 | 1047 | | opts.CopyFromTemplate(Options.ServerOptions); |
| | 121 | 1048 | | }); |
| | 61 | 1049 | | } |
| | | 1050 | | |
| | | 1051 | | /// <summary> |
| | | 1052 | | /// Configures named pipe listeners if supported on the current platform. |
| | | 1053 | | /// </summary> |
| | | 1054 | | internal void ConfigureNamedPipes() |
| | | 1055 | | { |
| | 62 | 1056 | | if (Options.NamedPipeOptions is not null) |
| | | 1057 | | { |
| | 1 | 1058 | | if (OperatingSystem.IsWindows()) |
| | | 1059 | | { |
| | 0 | 1060 | | _ = Builder.WebHost.UseNamedPipes(opts => |
| | 0 | 1061 | | { |
| | 0 | 1062 | | opts.ListenerQueueCount = Options.NamedPipeOptions.ListenerQueueCount; |
| | 0 | 1063 | | opts.MaxReadBufferSize = Options.NamedPipeOptions.MaxReadBufferSize; |
| | 0 | 1064 | | opts.MaxWriteBufferSize = Options.NamedPipeOptions.MaxWriteBufferSize; |
| | 0 | 1065 | | opts.CurrentUserOnly = Options.NamedPipeOptions.CurrentUserOnly; |
| | 0 | 1066 | | opts.PipeSecurity = Options.NamedPipeOptions.PipeSecurity; |
| | 0 | 1067 | | }); |
| | | 1068 | | } |
| | | 1069 | | else |
| | | 1070 | | { |
| | 1 | 1071 | | Logger.Verbose("Named pipe listeners configuration is supported only on Windows; skipping UseNamedPipes |
| | | 1072 | | } |
| | | 1073 | | } |
| | 62 | 1074 | | } |
| | | 1075 | | |
| | | 1076 | | /// <summary> |
| | | 1077 | | /// Configures HTTPS connection adapter defaults. |
| | | 1078 | | /// </summary> |
| | | 1079 | | /// <param name="serverOptions">The Kestrel server options to configure.</param> |
| | | 1080 | | internal void ConfigureHttpsAdapter(KestrelServerOptions serverOptions) |
| | | 1081 | | { |
| | 61 | 1082 | | if (Options.HttpsConnectionAdapter is not null) |
| | | 1083 | | { |
| | 0 | 1084 | | Logger.Verbose("Applying HTTPS connection adapter options from KestrunOptions."); |
| | | 1085 | | |
| | | 1086 | | // Apply HTTPS defaults if needed |
| | 0 | 1087 | | serverOptions.ConfigureHttpsDefaults(httpsOptions => |
| | 0 | 1088 | | { |
| | 0 | 1089 | | httpsOptions.SslProtocols = Options.HttpsConnectionAdapter.SslProtocols; |
| | 0 | 1090 | | httpsOptions.ClientCertificateMode = Options.HttpsConnectionAdapter.ClientCertificateMode; |
| | 0 | 1091 | | httpsOptions.ClientCertificateValidation = Options.HttpsConnectionAdapter.ClientCertificateValidation; |
| | 0 | 1092 | | httpsOptions.CheckCertificateRevocation = Options.HttpsConnectionAdapter.CheckCertificateRevocation; |
| | 0 | 1093 | | httpsOptions.ServerCertificate = Options.HttpsConnectionAdapter.ServerCertificate; |
| | 0 | 1094 | | httpsOptions.ServerCertificateChain = Options.HttpsConnectionAdapter.ServerCertificateChain; |
| | 0 | 1095 | | httpsOptions.ServerCertificateSelector = Options.HttpsConnectionAdapter.ServerCertificateSelector; |
| | 0 | 1096 | | httpsOptions.HandshakeTimeout = Options.HttpsConnectionAdapter.HandshakeTimeout; |
| | 0 | 1097 | | httpsOptions.OnAuthenticate = Options.HttpsConnectionAdapter.OnAuthenticate; |
| | 0 | 1098 | | }); |
| | | 1099 | | } |
| | 61 | 1100 | | } |
| | | 1101 | | |
| | | 1102 | | /// <summary> |
| | | 1103 | | /// Binds all configured listeners (Unix sockets, named pipes, TCP) to the server. |
| | | 1104 | | /// </summary> |
| | | 1105 | | /// <param name="serverOptions">The Kestrel server options to configure.</param> |
| | | 1106 | | internal void BindListeners(KestrelServerOptions serverOptions) |
| | | 1107 | | { |
| | | 1108 | | // Unix domain socket listeners |
| | 124 | 1109 | | foreach (var unixSocket in Options.ListenUnixSockets) |
| | | 1110 | | { |
| | 0 | 1111 | | if (!string.IsNullOrWhiteSpace(unixSocket)) |
| | | 1112 | | { |
| | 0 | 1113 | | Logger.Verbose("Binding Unix socket: {Sock}", unixSocket); |
| | 0 | 1114 | | serverOptions.ListenUnixSocket(unixSocket); |
| | | 1115 | | // NOTE: control access via directory perms/umask; UDS file perms are inherited from process umask |
| | | 1116 | | // Prefer placing the socket under a group-owned dir (e.g., /var/run/kestrun) with 0770. |
| | | 1117 | | } |
| | | 1118 | | } |
| | | 1119 | | |
| | | 1120 | | // Named pipe listeners |
| | 124 | 1121 | | foreach (var namedPipeName in Options.NamedPipeNames) |
| | | 1122 | | { |
| | 0 | 1123 | | if (!string.IsNullOrWhiteSpace(namedPipeName)) |
| | | 1124 | | { |
| | 0 | 1125 | | Logger.Verbose("Binding Named Pipe: {Pipe}", namedPipeName); |
| | 0 | 1126 | | serverOptions.ListenNamedPipe(namedPipeName); |
| | | 1127 | | } |
| | | 1128 | | } |
| | | 1129 | | |
| | | 1130 | | // TCP listeners |
| | 192 | 1131 | | foreach (var opt in Options.Listeners) |
| | | 1132 | | { |
| | 34 | 1133 | | serverOptions.Listen(opt.IPAddress, opt.Port, listenOptions => |
| | 34 | 1134 | | { |
| | 34 | 1135 | | listenOptions.Protocols = opt.Protocols; |
| | 34 | 1136 | | listenOptions.DisableAltSvcHeader = opt.DisableAltSvcHeader; |
| | 34 | 1137 | | if (opt.UseHttps && opt.X509Certificate is not null) |
| | 34 | 1138 | | { |
| | 2 | 1139 | | _ = listenOptions.UseHttps(opt.X509Certificate); |
| | 34 | 1140 | | } |
| | 34 | 1141 | | if (opt.UseConnectionLogging) |
| | 34 | 1142 | | { |
| | 0 | 1143 | | _ = listenOptions.UseConnectionLogging(); |
| | 34 | 1144 | | } |
| | 68 | 1145 | | }); |
| | | 1146 | | } |
| | 62 | 1147 | | } |
| | | 1148 | | |
| | | 1149 | | /// <summary> |
| | | 1150 | | /// Logs the configured endpoints after building the application. |
| | | 1151 | | /// </summary> |
| | | 1152 | | internal void LogConfiguredEndpoints() |
| | | 1153 | | { |
| | | 1154 | | // build the app to validate configuration |
| | 61 | 1155 | | _app = Build(); |
| | | 1156 | | // Log configured endpoints |
| | 61 | 1157 | | var dataSource = _app.Services.GetRequiredService<EndpointDataSource>(); |
| | | 1158 | | |
| | 61 | 1159 | | if (dataSource.Endpoints.Count == 0) |
| | | 1160 | | { |
| | 61 | 1161 | | Logger.Warning("EndpointDataSource is empty. No endpoints configured."); |
| | | 1162 | | } |
| | | 1163 | | else |
| | | 1164 | | { |
| | 0 | 1165 | | foreach (var ep in dataSource.Endpoints) |
| | | 1166 | | { |
| | 0 | 1167 | | Logger.Information("➡️ Endpoint: {DisplayName}", ep.DisplayName); |
| | | 1168 | | } |
| | | 1169 | | } |
| | 0 | 1170 | | } |
| | | 1171 | | |
| | | 1172 | | /// <summary> |
| | | 1173 | | /// Handles configuration errors and wraps them with meaningful messages. |
| | | 1174 | | /// </summary> |
| | | 1175 | | /// <param name="ex">The exception that occurred during configuration.</param> |
| | | 1176 | | /// <exception cref="InvalidOperationException">Always thrown with wrapped exception.</exception> |
| | | 1177 | | internal void HandleConfigurationError(Exception ex) |
| | | 1178 | | { |
| | 1 | 1179 | | Logger.Error(ex, "Error applying configuration: {Message}", ex.Message); |
| | 1 | 1180 | | throw new InvalidOperationException("Failed to apply configuration.", ex); |
| | | 1181 | | } |
| | | 1182 | | |
| | | 1183 | | /// <summary> |
| | | 1184 | | /// Applies the configured options to the Kestrel server and initializes the runspace pool. |
| | | 1185 | | /// </summary> |
| | | 1186 | | /// <param name="userVariables">User-defined variables to inject into the runspace pool.</param> |
| | | 1187 | | /// <param name="userFunctions">User-defined functions to inject into the runspace pool.</param> |
| | | 1188 | | /// <param name="userCallbacks">User-defined callback functions for OpenAPI classes.</param> |
| | | 1189 | | public void EnableConfiguration(Dictionary<string, object>? userVariables = null, Dictionary<string, string>? userFu |
| | | 1190 | | { |
| | 81 | 1191 | | if (!ValidateConfiguration()) |
| | | 1192 | | { |
| | 21 | 1193 | | return; |
| | | 1194 | | } |
| | | 1195 | | |
| | | 1196 | | try |
| | | 1197 | | { |
| | 60 | 1198 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1199 | | { |
| | 37 | 1200 | | Logger.Debug("Applying configuration to KestrunHost."); |
| | | 1201 | | } |
| | | 1202 | | // Inject user variables into shared state |
| | 60 | 1203 | | _ = ApplyUserVarsToState(userVariables); |
| | | 1204 | | |
| | | 1205 | | // Scan for OpenAPI component annotations in the main script. |
| | | 1206 | | // In C#-only scenarios (including xUnit tests), there may be no PowerShell entry script. |
| | 60 | 1207 | | ComponentAnnotations = !string.IsNullOrWhiteSpace(KestrunHostManager.EntryScriptPath) |
| | 60 | 1208 | | && File.Exists(KestrunHostManager.EntryScriptPath) |
| | 60 | 1209 | | ? OpenApiComponentAnnotationScanner.ScanFromPath(mainPath: KestrunHostManager.EntryScriptPath) |
| | 60 | 1210 | | : null; |
| | | 1211 | | |
| | | 1212 | | // Export OpenAPI classes from PowerShell |
| | 60 | 1213 | | var openApiClassesPath = ExportOpenApiClasses(userCallbacks); |
| | | 1214 | | // Initialize PowerShell runspace pool |
| | 60 | 1215 | | InitializeRunspacePool(userVariables: null, userFunctions: userFunctions, openApiClassesPath: openApiClasses |
| | | 1216 | | // Configure Kestrel server |
| | 60 | 1217 | | ConfigureKestrelBase(); |
| | | 1218 | | // Configure named pipe listeners if any |
| | 60 | 1219 | | ConfigureNamedPipes(); |
| | | 1220 | | // Normalize HTTP/3 listeners and configure QUIC if supported, or adjust listeners if QUIC is unavailable |
| | 60 | 1221 | | NormalizeHttp3ListenersAndConfigureQuic(); |
| | | 1222 | | |
| | | 1223 | | // Apply Kestrel listeners and HTTPS settings |
| | 60 | 1224 | | _ = Builder.WebHost.ConfigureKestrel(serverOptions => |
| | 60 | 1225 | | { |
| | 60 | 1226 | | ConfigureHttpsAdapter(serverOptions); |
| | 60 | 1227 | | BindListeners(serverOptions); |
| | 120 | 1228 | | }); |
| | | 1229 | | |
| | | 1230 | | // Generate OpenAPI components after runspace is ready |
| | 126 | 1231 | | foreach (var openApiDocument in OpenApiDocumentDescriptor.Values) |
| | | 1232 | | { |
| | 3 | 1233 | | openApiDocument.GenerateComponents(); |
| | | 1234 | | } |
| | | 1235 | | |
| | | 1236 | | // Log configured endpoints after building |
| | 60 | 1237 | | LogConfiguredEndpoints(); |
| | | 1238 | | |
| | | 1239 | | // Register default probes after endpoints are logged but before marking configured |
| | 60 | 1240 | | RegisterDefaultHealthProbes(); |
| | 60 | 1241 | | IsConfigured = true; |
| | 60 | 1242 | | Logger.Information("Configuration applied successfully."); |
| | 60 | 1243 | | } |
| | 0 | 1244 | | catch (Exception ex) |
| | | 1245 | | { |
| | 0 | 1246 | | HandleConfigurationError(ex); |
| | 0 | 1247 | | } |
| | 60 | 1248 | | } |
| | | 1249 | | |
| | | 1250 | | /// <summary> |
| | | 1251 | | /// Normalizes listeners that request HTTP/3 and configures QUIC when supported. |
| | | 1252 | | /// </summary> |
| | | 1253 | | /// <remarks> |
| | | 1254 | | /// When QUIC is unavailable, HTTP/3-only listeners fail fast with an explicit error. |
| | | 1255 | | /// Mixed listeners are left unchanged so Kestrel can negotiate fallback protocols. |
| | | 1256 | | /// </remarks> |
| | | 1257 | | private void NormalizeHttp3ListenersAndConfigureQuic() |
| | | 1258 | | { |
| | 60 | 1259 | | var http3Listeners = Options.Listeners |
| | 33 | 1260 | | .Where(listener => (listener.Protocols & HttpProtocols.Http3) != 0) |
| | 60 | 1261 | | .ToList(); |
| | | 1262 | | |
| | 60 | 1263 | | if (http3Listeners.Count == 0) |
| | | 1264 | | { |
| | 60 | 1265 | | return; |
| | | 1266 | | } |
| | | 1267 | | |
| | 0 | 1268 | | if (IsQuicSupported()) |
| | | 1269 | | { |
| | 0 | 1270 | | var ports = string.Join(", ", http3Listeners.Select(listener => listener.Port)); |
| | 0 | 1271 | | Logger.Information("Enabling QUIC support for HTTP/3 listeners on port(s): {Ports}.", ports); |
| | 0 | 1272 | | _ = Builder.WebHost.UseQuic(); |
| | 0 | 1273 | | return; |
| | | 1274 | | } |
| | | 1275 | | |
| | 0 | 1276 | | Logger.Warning("HTTP/3 was requested for {Count} listener(s), but QUIC is not supported on this platform/runtime |
| | | 1277 | | |
| | 0 | 1278 | | var http3OnlyListeners = http3Listeners |
| | 0 | 1279 | | .Where(listener => listener.Protocols == HttpProtocols.Http3) |
| | 0 | 1280 | | .Select(listener => listener.Port) |
| | 0 | 1281 | | .ToArray(); |
| | | 1282 | | |
| | 0 | 1283 | | if (http3OnlyListeners.Length > 0) |
| | | 1284 | | { |
| | 0 | 1285 | | var ports = string.Join(", ", http3OnlyListeners); |
| | 0 | 1286 | | throw new InvalidOperationException($"Unable to bind HTTP/3-only endpoint(s) on port(s): {ports}. QUIC is no |
| | | 1287 | | } |
| | | 1288 | | |
| | 0 | 1289 | | Logger.Information("Continuing with mixed HTTP protocol listeners unchanged; Kestrel will negotiate fallback pro |
| | 0 | 1290 | | } |
| | | 1291 | | |
| | | 1292 | | /// <summary> |
| | | 1293 | | /// Determines whether QUIC is supported by the current runtime/platform without directly calling preview-only APIs. |
| | | 1294 | | /// </summary> |
| | | 1295 | | /// <returns><c>true</c> when QUIC support is available; otherwise, <c>false</c>.</returns> |
| | 8 | 1296 | | public static bool IsQuicSupported() => _isQuicSupported.Value; |
| | | 1297 | | |
| | | 1298 | | /// <summary> |
| | | 1299 | | /// Cached reflection-based evaluator for QUIC support, using QuicListener.IsSupported. |
| | | 1300 | | /// </summary> |
| | 1 | 1301 | | private static readonly Lazy<bool> _isQuicSupported = new(() => |
| | 1 | 1302 | | { |
| | 1 | 1303 | | var quicListenerType = Type.GetType("System.Net.Quic.QuicListener, System.Net.Quic", throwOnError: false); |
| | 1 | 1304 | | var isSupportedProperty = quicListenerType?.GetProperty("IsSupported", BindingFlags.Public | BindingFlags.Static |
| | 1 | 1305 | | return isSupportedProperty?.GetValue(null) as bool? ?? false; |
| | 1 | 1306 | | }); |
| | | 1307 | | |
| | | 1308 | | /// <summary> |
| | | 1309 | | /// Applies user-defined variables to the shared state. |
| | | 1310 | | /// </summary> |
| | | 1311 | | /// <param name="userVariables">User-defined variables to inject into the shared state.</param> |
| | | 1312 | | /// <returns>True if all variables were successfully applied; otherwise, false.</returns> |
| | | 1313 | | private bool ApplyUserVarsToState(Dictionary<string, object>? userVariables) |
| | | 1314 | | { |
| | 60 | 1315 | | var statusSet = true; |
| | 60 | 1316 | | if (userVariables is not null) |
| | | 1317 | | { |
| | 4 | 1318 | | foreach (var v in userVariables) |
| | | 1319 | | { |
| | 1 | 1320 | | statusSet &= SharedState.Set(v.Key, v.Value, true); |
| | | 1321 | | } |
| | | 1322 | | } |
| | 60 | 1323 | | return statusSet; |
| | | 1324 | | } |
| | | 1325 | | |
| | | 1326 | | /// <summary> |
| | | 1327 | | /// Exports OpenAPI classes from PowerShell. |
| | | 1328 | | /// </summary> |
| | | 1329 | | /// <param name="userCallbacks">User-defined callbacks for OpenAPI class export.</param> |
| | | 1330 | | private string ExportOpenApiClasses(Dictionary<string, string>? userCallbacks) |
| | | 1331 | | { |
| | | 1332 | | // Export OpenAPI classes from PowerShell |
| | 60 | 1333 | | var openApiClassesPath = PowerShellOpenApiClassExporter.ExportOpenApiClasses(userCallbacks: userCallbacks); |
| | 60 | 1334 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1335 | | { |
| | 37 | 1336 | | if (string.IsNullOrWhiteSpace(openApiClassesPath)) |
| | | 1337 | | { |
| | 37 | 1338 | | Logger.Debug("No OpenAPI classes exported from PowerShell."); |
| | | 1339 | | } |
| | | 1340 | | else |
| | | 1341 | | { |
| | 0 | 1342 | | Logger.Debug("Exported OpenAPI classes from PowerShell: {path}", openApiClassesPath); |
| | | 1343 | | } |
| | | 1344 | | } |
| | 60 | 1345 | | return openApiClassesPath; |
| | | 1346 | | } |
| | | 1347 | | |
| | | 1348 | | /// <summary> |
| | | 1349 | | /// Registers built-in default health probes (idempotent). Currently includes disk space probe. |
| | | 1350 | | /// </summary> |
| | | 1351 | | private void RegisterDefaultHealthProbes() |
| | | 1352 | | { |
| | | 1353 | | try |
| | | 1354 | | { |
| | | 1355 | | // Avoid duplicate registration if user already added a probe named "disk". |
| | 60 | 1356 | | lock (_healthProbeLock) |
| | | 1357 | | { |
| | 60 | 1358 | | if (HealthProbes.Any(p => string.Equals(p.Name, "disk", StringComparison.OrdinalIgnoreCase))) |
| | | 1359 | | { |
| | 0 | 1360 | | return; // already present |
| | | 1361 | | } |
| | 60 | 1362 | | } |
| | | 1363 | | |
| | 60 | 1364 | | var tags = new[] { IProbe.TAG_SELF }; // neutral tag; user can filter by name if needed |
| | 60 | 1365 | | var diskProbe = new DiskSpaceProbe("disk", tags); |
| | 60 | 1366 | | RegisterProbeInternal(diskProbe); |
| | 60 | 1367 | | } |
| | 0 | 1368 | | catch (Exception ex) |
| | | 1369 | | { |
| | 0 | 1370 | | Logger.Warning(ex, "Failed to register default disk space probe."); |
| | 0 | 1371 | | } |
| | 60 | 1372 | | } |
| | | 1373 | | |
| | | 1374 | | #endregion |
| | | 1375 | | #region Builder |
| | | 1376 | | /* More information about the KestrunHost class |
| | | 1377 | | https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.webapplication?view=aspnetcore-8.0 |
| | | 1378 | | |
| | | 1379 | | */ |
| | | 1380 | | |
| | | 1381 | | /// <summary> |
| | | 1382 | | /// Builds the WebApplication. |
| | | 1383 | | /// This method applies all queued services and middleware stages, |
| | | 1384 | | /// and returns the built WebApplication instance. |
| | | 1385 | | /// </summary> |
| | | 1386 | | /// <returns>The built WebApplication.</returns> |
| | | 1387 | | /// <exception cref="InvalidOperationException"></exception> |
| | | 1388 | | public WebApplication Build() |
| | | 1389 | | { |
| | 110 | 1390 | | ValidateBuilderState(); |
| | 110 | 1391 | | ApplyQueuedServices(); |
| | 110 | 1392 | | BuildWebApplication(); |
| | 110 | 1393 | | ConfigureBuiltInMiddleware(); |
| | 110 | 1394 | | LogApplicationInfo(); |
| | 110 | 1395 | | ApplyQueuedMiddleware(); |
| | 110 | 1396 | | ApplyFeatures(); |
| | | 1397 | | |
| | 110 | 1398 | | return _app!; |
| | | 1399 | | } |
| | | 1400 | | |
| | | 1401 | | /// <summary> |
| | | 1402 | | /// Validates that the builder is properly initialized before building. |
| | | 1403 | | /// </summary> |
| | | 1404 | | /// <exception cref="InvalidOperationException">Thrown when the builder is not initialized.</exception> |
| | | 1405 | | private void ValidateBuilderState() |
| | | 1406 | | { |
| | 110 | 1407 | | if (Builder == null) |
| | | 1408 | | { |
| | 0 | 1409 | | throw new InvalidOperationException("Call CreateBuilder() first."); |
| | | 1410 | | } |
| | 110 | 1411 | | } |
| | | 1412 | | |
| | | 1413 | | /// <summary> |
| | | 1414 | | /// Applies all queued service configurations to the service collection. |
| | | 1415 | | /// </summary> |
| | | 1416 | | private void ApplyQueuedServices() |
| | | 1417 | | { |
| | 362 | 1418 | | foreach (var configure in _serviceQueue) |
| | | 1419 | | { |
| | 71 | 1420 | | configure(Builder.Services); |
| | | 1421 | | } |
| | 110 | 1422 | | } |
| | | 1423 | | |
| | | 1424 | | /// <summary> |
| | | 1425 | | /// Builds the WebApplication instance from the configured builder. |
| | | 1426 | | /// </summary> |
| | | 1427 | | private void BuildWebApplication() |
| | | 1428 | | { |
| | 110 | 1429 | | _app = Builder.Build(); |
| | 110 | 1430 | | Logger.Information("Application built successfully."); |
| | | 1431 | | |
| | 110 | 1432 | | PopulateAppUrlsFromListeners(); |
| | | 1433 | | |
| | | 1434 | | // 🔔 SignalR shutdown notification |
| | 110 | 1435 | | _ = _app.Lifetime.ApplicationStopping.Register(() => |
| | 110 | 1436 | | { |
| | 110 | 1437 | | try |
| | 110 | 1438 | | { |
| | 24 | 1439 | | using var scope = _app.Services.CreateScope(); |
| | 110 | 1440 | | |
| | 24 | 1441 | | var isService = scope.ServiceProvider.GetService<IServiceProviderIsService>(); |
| | 24 | 1442 | | if (isService?.IsService(typeof(IHubContext<SignalR.KestrunHub>)) != true) |
| | 110 | 1443 | | { |
| | 24 | 1444 | | Logger.Debug("SignalR hub context not available. Skipping shutdown notification."); |
| | 24 | 1445 | | return; |
| | 110 | 1446 | | } |
| | 110 | 1447 | | |
| | 0 | 1448 | | var hub = scope.ServiceProvider.GetRequiredService<IHubContext<SignalR.KestrunHub>>(); |
| | 0 | 1449 | | _ = hub.Clients.All.SendAsync("serverShutdown", "Server stopping"); |
| | 0 | 1450 | | Logger.Information("Sent SignalR shutdown notification to clients."); |
| | 0 | 1451 | | } |
| | 0 | 1452 | | catch (Exception ex) |
| | 110 | 1453 | | { |
| | 0 | 1454 | | Logger.Debug(ex, "Failed to send SignalR shutdown notification."); |
| | 0 | 1455 | | } |
| | 134 | 1456 | | }); |
| | 110 | 1457 | | } |
| | | 1458 | | |
| | | 1459 | | /// <summary> |
| | | 1460 | | /// Adds listener URLs to the application URL list when none are present. |
| | | 1461 | | /// </summary> |
| | | 1462 | | private void PopulateAppUrlsFromListeners() |
| | | 1463 | | { |
| | 110 | 1464 | | if (_app is null || _app.Urls.Count > 0) |
| | | 1465 | | { |
| | 0 | 1466 | | return; |
| | | 1467 | | } |
| | | 1468 | | |
| | 286 | 1469 | | foreach (var listener in Options.Listeners) |
| | | 1470 | | { |
| | 33 | 1471 | | var host = listener.IPAddress == null || IPAddress.Any.Equals(listener.IPAddress) || IPAddress.IPv6Any.Equal |
| | 33 | 1472 | | ? "localhost" |
| | 33 | 1473 | | : listener.IPAddress.ToString(); |
| | | 1474 | | |
| | 33 | 1475 | | if (listener.IPAddress != null && listener.IPAddress.AddressFamily == AddressFamily.InterNetworkV6 && !host. |
| | | 1476 | | { |
| | 1 | 1477 | | host = $"[{host}]"; |
| | | 1478 | | } |
| | | 1479 | | |
| | 33 | 1480 | | var scheme = listener.UseHttps ? "https" : "http"; |
| | 33 | 1481 | | _app.Urls.Add($"{scheme}://{host}:{listener.Port}"); |
| | | 1482 | | } |
| | 110 | 1483 | | } |
| | | 1484 | | |
| | | 1485 | | /// <summary> |
| | | 1486 | | /// Resolves an ephemeral port for the specified address by binding a temporary listener. |
| | | 1487 | | /// </summary> |
| | | 1488 | | /// <param name="ipAddress">The address to bind to when selecting the port.</param> |
| | | 1489 | | /// <returns>An available port number.</returns> |
| | | 1490 | | private static int ResolveEphemeralPort(IPAddress ipAddress) |
| | | 1491 | | { |
| | 23 | 1492 | | var bindAddress = ipAddress; |
| | 23 | 1493 | | if (IPAddress.Any.Equals(bindAddress)) |
| | | 1494 | | { |
| | 1 | 1495 | | bindAddress = IPAddress.Loopback; |
| | | 1496 | | } |
| | 22 | 1497 | | else if (IPAddress.IPv6Any.Equals(bindAddress)) |
| | | 1498 | | { |
| | 0 | 1499 | | bindAddress = IPAddress.IPv6Loopback; |
| | | 1500 | | } |
| | | 1501 | | |
| | 23 | 1502 | | var listener = new TcpListener(bindAddress, 0); |
| | 23 | 1503 | | listener.Start(); |
| | 23 | 1504 | | var port = ((IPEndPoint)listener.LocalEndpoint).Port; |
| | 23 | 1505 | | listener.Stop(); |
| | 23 | 1506 | | return port; |
| | | 1507 | | } |
| | | 1508 | | |
| | | 1509 | | /// <summary> |
| | | 1510 | | /// Configures built-in middleware components in the correct order. |
| | | 1511 | | /// </summary> |
| | | 1512 | | private void ConfigureBuiltInMiddleware() |
| | | 1513 | | { |
| | | 1514 | | // Configure routing |
| | 110 | 1515 | | ConfigureRouting(); |
| | | 1516 | | // Configure CORS |
| | 110 | 1517 | | ConfigureCors(); |
| | | 1518 | | // Configure exception handling |
| | 110 | 1519 | | ConfigureExceptionHandling(); |
| | | 1520 | | // Configure forwarded headers |
| | 110 | 1521 | | ConfigureForwardedHeaders(); |
| | | 1522 | | // Configure status code pages |
| | 110 | 1523 | | ConfigureStatusCodePages(); |
| | | 1524 | | // Configure PowerShell runtime |
| | 110 | 1525 | | ConfigurePowerShellRuntime(); |
| | 110 | 1526 | | } |
| | | 1527 | | |
| | | 1528 | | /// <summary> |
| | | 1529 | | /// Configures routing middleware. |
| | | 1530 | | /// </summary> |
| | | 1531 | | private void ConfigureRouting() |
| | | 1532 | | { |
| | 110 | 1533 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1534 | | { |
| | 82 | 1535 | | Logger.Debug("Enabling routing middleware."); |
| | | 1536 | | } |
| | 110 | 1537 | | _ = _app!.UseRouting(); |
| | 110 | 1538 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1539 | | { |
| | 82 | 1540 | | Logger.Debug("Routing middleware is enabled."); |
| | | 1541 | | } |
| | 110 | 1542 | | } |
| | | 1543 | | |
| | | 1544 | | /// <summary> |
| | | 1545 | | /// Configures CORS middleware if a CORS policy is defined. |
| | | 1546 | | /// </summary> |
| | | 1547 | | private void ConfigureCors() |
| | | 1548 | | { |
| | 110 | 1549 | | if (CorsPolicyDefined) |
| | | 1550 | | { |
| | 0 | 1551 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1552 | | { |
| | 0 | 1553 | | Logger.Debug("Enabling CORS middleware."); |
| | | 1554 | | } |
| | 0 | 1555 | | _ = _app!.UseCors(); |
| | 0 | 1556 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1557 | | { |
| | 0 | 1558 | | Logger.Debug("CORS middleware is enabled."); |
| | | 1559 | | } |
| | | 1560 | | } |
| | 110 | 1561 | | } |
| | | 1562 | | |
| | | 1563 | | /// <summary> |
| | | 1564 | | /// Configures exception handling middleware if enabled. |
| | | 1565 | | /// </summary> |
| | | 1566 | | private void ConfigureExceptionHandling() |
| | | 1567 | | { |
| | 110 | 1568 | | if (ExceptionOptions is not null) |
| | | 1569 | | { |
| | 5 | 1570 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1571 | | { |
| | 0 | 1572 | | Logger.Debug("Enabling exception handling middleware."); |
| | | 1573 | | } |
| | 5 | 1574 | | _ = ExceptionOptions.DeveloperExceptionPageOptions is not null |
| | 5 | 1575 | | ? _app!.UseDeveloperExceptionPage(ExceptionOptions.DeveloperExceptionPageOptions) |
| | 5 | 1576 | | : _app!.UseExceptionHandler(ExceptionOptions); |
| | 5 | 1577 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1578 | | { |
| | 0 | 1579 | | Logger.Debug("Exception handling middleware is enabled."); |
| | | 1580 | | } |
| | | 1581 | | } |
| | 110 | 1582 | | } |
| | | 1583 | | |
| | | 1584 | | /// <summary> |
| | | 1585 | | /// Configures forwarded headers middleware if enabled. |
| | | 1586 | | /// </summary> |
| | | 1587 | | private void ConfigureForwardedHeaders() |
| | | 1588 | | { |
| | 110 | 1589 | | if (ForwardedHeaderOptions is not null) |
| | | 1590 | | { |
| | 3 | 1591 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1592 | | { |
| | 0 | 1593 | | Logger.Debug("Enabling forwarded headers middleware."); |
| | | 1594 | | } |
| | 3 | 1595 | | _ = _app!.UseForwardedHeaders(ForwardedHeaderOptions); |
| | 3 | 1596 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1597 | | { |
| | 0 | 1598 | | Logger.Debug("Forwarded headers middleware is enabled."); |
| | | 1599 | | } |
| | | 1600 | | } |
| | 110 | 1601 | | } |
| | | 1602 | | |
| | | 1603 | | /// <summary> |
| | | 1604 | | /// Configures status code pages middleware if enabled. |
| | | 1605 | | /// </summary> |
| | | 1606 | | private void ConfigureStatusCodePages() |
| | | 1607 | | { |
| | | 1608 | | // Register StatusCodePages BEFORE language runtimes so that re-executed requests |
| | | 1609 | | // pass through language middleware again (and get fresh RouteValues/context). |
| | 110 | 1610 | | if (StatusCodeOptions is not null) |
| | | 1611 | | { |
| | 0 | 1612 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1613 | | { |
| | 0 | 1614 | | Logger.Debug("Enabling status code pages middleware."); |
| | | 1615 | | } |
| | 0 | 1616 | | _ = _app!.UseStatusCodePages(StatusCodeOptions); |
| | 0 | 1617 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1618 | | { |
| | 0 | 1619 | | Logger.Debug("Status code pages middleware is enabled."); |
| | | 1620 | | } |
| | | 1621 | | } |
| | 110 | 1622 | | } |
| | | 1623 | | |
| | | 1624 | | /// <summary> |
| | | 1625 | | /// Configures PowerShell runtime middleware if enabled. |
| | | 1626 | | /// </summary> |
| | | 1627 | | /// <exception cref="InvalidOperationException">Thrown when PowerShell is enabled but runspace pool is not initializ |
| | | 1628 | | private void ConfigurePowerShellRuntime() |
| | | 1629 | | { |
| | 110 | 1630 | | if (PowershellMiddlewareEnabled) |
| | | 1631 | | { |
| | 0 | 1632 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1633 | | { |
| | 0 | 1634 | | Logger.Debug("Enabling PowerShell middleware."); |
| | | 1635 | | } |
| | | 1636 | | |
| | 0 | 1637 | | if (_runspacePool is null) |
| | | 1638 | | { |
| | 0 | 1639 | | throw new InvalidOperationException("Runspace pool is not initialized. Call EnableConfiguration first.") |
| | | 1640 | | } |
| | | 1641 | | |
| | 0 | 1642 | | Logger.Information("Adding PowerShell runtime"); |
| | 0 | 1643 | | _ = _app!.UseLanguageRuntime( |
| | 0 | 1644 | | ScriptLanguage.PowerShell, |
| | 0 | 1645 | | b => b.UsePowerShellRunspace(_runspacePool)); |
| | | 1646 | | |
| | 0 | 1647 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1648 | | { |
| | 0 | 1649 | | Logger.Debug("PowerShell middleware is enabled."); |
| | | 1650 | | } |
| | | 1651 | | } |
| | 110 | 1652 | | } |
| | | 1653 | | |
| | | 1654 | | /// <summary> |
| | | 1655 | | /// Logs application information including working directory and Pages directory contents. |
| | | 1656 | | /// </summary> |
| | | 1657 | | private void LogApplicationInfo() |
| | | 1658 | | { |
| | 110 | 1659 | | Logger.Information("CWD: {CWD}", GetSafeCurrentDirectory()); |
| | 110 | 1660 | | Logger.Information("ContentRoot: {Root}", _app!.Environment.ContentRootPath); |
| | 110 | 1661 | | LogPagesDirectory(); |
| | 110 | 1662 | | } |
| | | 1663 | | |
| | | 1664 | | /// <summary> |
| | | 1665 | | /// Logs information about the Pages directory and its contents. |
| | | 1666 | | /// </summary> |
| | | 1667 | | private void LogPagesDirectory() |
| | | 1668 | | { |
| | 110 | 1669 | | var pagesDir = Path.Combine(_app!.Environment.ContentRootPath, "Pages"); |
| | 110 | 1670 | | Logger.Information("Pages Dir: {PagesDir}", pagesDir); |
| | | 1671 | | |
| | 110 | 1672 | | if (Directory.Exists(pagesDir)) |
| | | 1673 | | { |
| | 2 | 1674 | | foreach (var file in Directory.GetFiles(pagesDir, "*.*", SearchOption.AllDirectories)) |
| | | 1675 | | { |
| | 0 | 1676 | | Logger.Information("Pages file: {File}", file); |
| | | 1677 | | } |
| | | 1678 | | } |
| | | 1679 | | else |
| | | 1680 | | { |
| | 109 | 1681 | | Logger.Warning("Pages directory does not exist: {PagesDir}", pagesDir); |
| | | 1682 | | } |
| | 109 | 1683 | | } |
| | | 1684 | | |
| | | 1685 | | /// <summary> |
| | | 1686 | | /// Applies all queued middleware stages to the application pipeline. |
| | | 1687 | | /// </summary> |
| | | 1688 | | private void ApplyQueuedMiddleware() |
| | | 1689 | | { |
| | 314 | 1690 | | foreach (var stage in _middlewareQueue) |
| | | 1691 | | { |
| | 47 | 1692 | | stage(_app!); |
| | | 1693 | | } |
| | 110 | 1694 | | } |
| | | 1695 | | |
| | | 1696 | | /// <summary> |
| | | 1697 | | /// Applies all queued features to the host. |
| | | 1698 | | /// </summary> |
| | | 1699 | | private void ApplyFeatures() |
| | | 1700 | | { |
| | 224 | 1701 | | foreach (var feature in FeatureQueue) |
| | | 1702 | | { |
| | 2 | 1703 | | feature(this); |
| | | 1704 | | } |
| | 110 | 1705 | | } |
| | | 1706 | | |
| | | 1707 | | /// <summary> |
| | | 1708 | | /// Returns true if the specified service type has already been registered in the IServiceCollection. |
| | | 1709 | | /// </summary> |
| | | 1710 | | public bool IsServiceRegistered(Type serviceType) |
| | 798 | 1711 | | => Builder?.Services?.Any(sd => sd.ServiceType == serviceType) ?? false; |
| | | 1712 | | |
| | | 1713 | | /// <summary> |
| | | 1714 | | /// Generic convenience overload. |
| | | 1715 | | /// </summary> |
| | 0 | 1716 | | public bool IsServiceRegistered<TService>() => IsServiceRegistered(typeof(TService)); |
| | | 1717 | | |
| | | 1718 | | /// <summary> |
| | | 1719 | | /// Adds a service configuration action to the service queue. |
| | | 1720 | | /// This action will be executed when the services are built. |
| | | 1721 | | /// </summary> |
| | | 1722 | | /// <param name="configure">The service configuration action.</param> |
| | | 1723 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1724 | | public KestrunHost AddService(Action<IServiceCollection> configure) |
| | | 1725 | | { |
| | 134 | 1726 | | _serviceQueue.Add(configure); |
| | 134 | 1727 | | return this; |
| | | 1728 | | } |
| | | 1729 | | |
| | | 1730 | | /// <summary> |
| | | 1731 | | /// Adds a middleware stage to the application pipeline. |
| | | 1732 | | /// </summary> |
| | | 1733 | | /// <param name="stage">The middleware stage to add.</param> |
| | | 1734 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1735 | | public KestrunHost Use(Action<IApplicationBuilder> stage) |
| | | 1736 | | { |
| | 109 | 1737 | | _middlewareQueue.Add(stage); |
| | 109 | 1738 | | return this; |
| | | 1739 | | } |
| | | 1740 | | |
| | | 1741 | | /// <summary> |
| | | 1742 | | /// Adds a feature configuration action to the feature queue. |
| | | 1743 | | /// This action will be executed when the features are applied. |
| | | 1744 | | /// </summary> |
| | | 1745 | | /// <param name="feature">The feature configuration action.</param> |
| | | 1746 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1747 | | public KestrunHost AddFeature(Action<KestrunHost> feature) |
| | | 1748 | | { |
| | 2 | 1749 | | FeatureQueue.Add(feature); |
| | 2 | 1750 | | return this; |
| | | 1751 | | } |
| | | 1752 | | |
| | | 1753 | | /// <summary> |
| | | 1754 | | /// Adds a scheduling feature to the Kestrun host, optionally specifying the maximum number of runspaces for the sch |
| | | 1755 | | /// </summary> |
| | | 1756 | | /// <param name="MaxRunspaces">The maximum number of runspaces for the scheduler. If null, uses the default value.</ |
| | | 1757 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1758 | | public KestrunHost AddScheduling(int? MaxRunspaces = null) |
| | | 1759 | | { |
| | 4 | 1760 | | return MaxRunspaces is not null and <= 0 |
| | 4 | 1761 | | ? throw new ArgumentOutOfRangeException(nameof(MaxRunspaces), "MaxRunspaces must be greater than zero.") |
| | 4 | 1762 | | : AddFeature(host => |
| | 4 | 1763 | | { |
| | 2 | 1764 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | 4 | 1765 | | { |
| | 2 | 1766 | | Logger.Debug("AddScheduling (deferred)"); |
| | 4 | 1767 | | } |
| | 4 | 1768 | | |
| | 2 | 1769 | | if (host._scheduler is null) |
| | 4 | 1770 | | { |
| | 1 | 1771 | | if (MaxRunspaces is not null and > 0) |
| | 4 | 1772 | | { |
| | 1 | 1773 | | Logger.Information("Setting MaxSchedulerRunspaces to {MaxRunspaces}", MaxRunspaces); |
| | 1 | 1774 | | host.Options.MaxSchedulerRunspaces = MaxRunspaces.Value; |
| | 4 | 1775 | | } |
| | 1 | 1776 | | Logger.Verbose("Creating SchedulerService with MaxSchedulerRunspaces={MaxRunspaces}", |
| | 1 | 1777 | | host.Options.MaxSchedulerRunspaces); |
| | 1 | 1778 | | var pool = host.CreateRunspacePool(host.Options.MaxSchedulerRunspaces); |
| | 1 | 1779 | | var logger = Logger.ForContext<KestrunHost>(); |
| | 1 | 1780 | | host.Scheduler = new SchedulerService(pool, logger); |
| | 4 | 1781 | | } |
| | 4 | 1782 | | else |
| | 4 | 1783 | | { |
| | 1 | 1784 | | Logger.Warning("SchedulerService already configured; skipping."); |
| | 4 | 1785 | | } |
| | 5 | 1786 | | }); |
| | | 1787 | | } |
| | | 1788 | | |
| | | 1789 | | /// <summary> |
| | | 1790 | | /// Adds the Tasks feature to run ad-hoc scripts with status/result/cancellation. |
| | | 1791 | | /// </summary> |
| | | 1792 | | /// <param name="MaxRunspaces">Optional max runspaces for the task PowerShell pool; when null uses scheduler default |
| | | 1793 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1794 | | public KestrunHost AddTasks(int? MaxRunspaces = null) |
| | | 1795 | | { |
| | 0 | 1796 | | return MaxRunspaces is not null and <= 0 |
| | 0 | 1797 | | ? throw new ArgumentOutOfRangeException(nameof(MaxRunspaces), "MaxRunspaces must be greater than zero.") |
| | 0 | 1798 | | : AddFeature(host => |
| | 0 | 1799 | | { |
| | 0 | 1800 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | 0 | 1801 | | { |
| | 0 | 1802 | | Logger.Debug("AddTasks (deferred)"); |
| | 0 | 1803 | | } |
| | 0 | 1804 | | |
| | 0 | 1805 | | if (host._tasks is null) |
| | 0 | 1806 | | { |
| | 0 | 1807 | | // Reuse scheduler pool sizing unless explicitly overridden |
| | 0 | 1808 | | if (MaxRunspaces is not null and > 0) |
| | 0 | 1809 | | { |
| | 0 | 1810 | | Logger.Information("Setting MaxTaskRunspaces to {MaxRunspaces}", MaxRunspaces); |
| | 0 | 1811 | | } |
| | 0 | 1812 | | var pool = host.CreateRunspacePool(MaxRunspaces ?? host.Options.MaxSchedulerRunspaces); |
| | 0 | 1813 | | var logger = Logger.ForContext<KestrunHost>(); |
| | 0 | 1814 | | host.Tasks = new KestrunTaskService(pool, logger); |
| | 0 | 1815 | | } |
| | 0 | 1816 | | else |
| | 0 | 1817 | | { |
| | 0 | 1818 | | Logger.Warning("KestrunTaskService already configured; skipping."); |
| | 0 | 1819 | | } |
| | 0 | 1820 | | }); |
| | | 1821 | | } |
| | | 1822 | | |
| | | 1823 | | /// <summary> |
| | | 1824 | | /// Adds MVC / API controllers to the application. |
| | | 1825 | | /// </summary> |
| | | 1826 | | /// <param name="cfg">The configuration options for MVC / API controllers.</param> |
| | | 1827 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1828 | | public KestrunHost AddControllers(Action<Microsoft.AspNetCore.Mvc.MvcOptions>? cfg = null) |
| | | 1829 | | { |
| | 0 | 1830 | | return AddService(services => |
| | 0 | 1831 | | { |
| | 0 | 1832 | | var builder = services.AddControllers(); |
| | 0 | 1833 | | if (cfg != null) |
| | 0 | 1834 | | { |
| | 0 | 1835 | | _ = builder.ConfigureApplicationPartManager(pm => { }); // customise if you wish |
| | 0 | 1836 | | } |
| | 0 | 1837 | | }); |
| | | 1838 | | } |
| | | 1839 | | |
| | | 1840 | | /// <summary> |
| | | 1841 | | /// Adds a PowerShell runtime to the application. |
| | | 1842 | | /// This middleware allows you to execute PowerShell scripts in response to HTTP requests. |
| | | 1843 | | /// </summary> |
| | | 1844 | | /// <param name="routePrefix">The route prefix to use for the PowerShell runtime.</param> |
| | | 1845 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 1846 | | public KestrunHost AddPowerShellRuntime(PathString? routePrefix = null) |
| | | 1847 | | { |
| | 1 | 1848 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1849 | | { |
| | 1 | 1850 | | Logger.Debug("Adding PowerShell runtime with route prefix: {RoutePrefix}", routePrefix); |
| | | 1851 | | } |
| | | 1852 | | |
| | 1 | 1853 | | return Use(app => |
| | 1 | 1854 | | { |
| | 1 | 1855 | | ArgumentNullException.ThrowIfNull(_runspacePool); |
| | 1 | 1856 | | // ── mount PowerShell at the root ── |
| | 1 | 1857 | | _ = app.UseLanguageRuntime( |
| | 1 | 1858 | | ScriptLanguage.PowerShell, |
| | 2 | 1859 | | b => b.UsePowerShellRunspace(_runspacePool)); |
| | 2 | 1860 | | }); |
| | | 1861 | | } |
| | | 1862 | | |
| | | 1863 | | /// <summary> |
| | | 1864 | | /// Adds the Realtime tag to the OpenAPI document if not already present. |
| | | 1865 | | /// </summary> |
| | | 1866 | | /// <param name="defTag"> OpenAPI document descriptor to which the Realtime tag will be added.</param> |
| | | 1867 | | private static void AddRealTimeTag(OpenApiDocDescriptor defTag) |
| | | 1868 | | { |
| | | 1869 | | // Add Realtime default tag if not present |
| | 2 | 1870 | | if (!defTag.ContainsTag("Realtime")) |
| | | 1871 | | { |
| | 2 | 1872 | | _ = defTag.AddTag(name: "Realtime", |
| | 2 | 1873 | | summary: "Real-time communication", |
| | 2 | 1874 | | description: "Protocols and endpoints for real-time, push-based communication such as SignalR and Server |
| | 2 | 1875 | | kind: "nav", |
| | 2 | 1876 | | externalDocs: new OpenApiExternalDocs |
| | 2 | 1877 | | { |
| | 2 | 1878 | | Description = "Real-time communication overview", |
| | 2 | 1879 | | Url = new Uri("https://learn.microsoft.com/aspnet/core/signalr/") |
| | 2 | 1880 | | }); |
| | | 1881 | | } |
| | 2 | 1882 | | } |
| | | 1883 | | |
| | | 1884 | | /// <summary> |
| | | 1885 | | /// Adds the SignalR tag to the OpenAPI document if not already present. |
| | | 1886 | | /// </summary> |
| | | 1887 | | /// <param name="defTag"> OpenAPI document descriptor to which the SignalR tag will be added.</param> |
| | | 1888 | | private static void AddSignalRTag(OpenApiDocDescriptor defTag) |
| | | 1889 | | { |
| | 0 | 1890 | | if (!defTag.ContainsTag(SignalROptions.DefaultTag)) |
| | | 1891 | | { |
| | 0 | 1892 | | _ = defTag.AddTag(name: SignalROptions.DefaultTag, |
| | 0 | 1893 | | description: "SignalR hubs providing real-time, bidirectional communication over persistent connections |
| | 0 | 1894 | | summary: "SignalR hubs", |
| | 0 | 1895 | | parent: "Realtime", |
| | 0 | 1896 | | externalDocs: new OpenApiExternalDocs |
| | 0 | 1897 | | { |
| | 0 | 1898 | | Description = "ASP.NET Core SignalR documentation", |
| | 0 | 1899 | | Url = new Uri("https://learn.microsoft.com/aspnet/core/signalr/introduction") |
| | 0 | 1900 | | }); |
| | | 1901 | | } |
| | 0 | 1902 | | } |
| | | 1903 | | |
| | | 1904 | | /// <summary> |
| | | 1905 | | /// Computes the SignalR negotiate endpoint path based on the hub path. |
| | | 1906 | | /// </summary> |
| | | 1907 | | /// <param name="hubPath">The hub route path.</param> |
| | | 1908 | | /// <returns>The negotiate path for the hub.</returns> |
| | | 1909 | | private static string GetSignalRNegotiatePath(string hubPath) |
| | 0 | 1910 | | => hubPath.EndsWith("/negotiate", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1911 | | ? hubPath |
| | 0 | 1912 | | : hubPath.TrimEnd('/') + "/negotiate"; |
| | | 1913 | | |
| | | 1914 | | /// <summary> |
| | | 1915 | | /// Creates a native route registration with no script body. |
| | | 1916 | | /// </summary> |
| | | 1917 | | /// <param name="pattern">The route pattern.</param> |
| | | 1918 | | /// <param name="verb">The HTTP verb for the route.</param> |
| | | 1919 | | /// <returns>A configured <see cref="MapRouteOptions"/> instance.</returns> |
| | | 1920 | | private static MapRouteOptions CreateNativeRouteOptions(string pattern, HttpVerb verb) |
| | 0 | 1921 | | => new() |
| | 0 | 1922 | | { |
| | 0 | 1923 | | Pattern = pattern, |
| | 0 | 1924 | | HttpVerbs = [verb], |
| | 0 | 1925 | | ScriptCode = new LanguageOptions |
| | 0 | 1926 | | { |
| | 0 | 1927 | | Language = ScriptLanguage.Native, |
| | 0 | 1928 | | Code = string.Empty |
| | 0 | 1929 | | } |
| | 0 | 1930 | | }; |
| | | 1931 | | |
| | | 1932 | | /// <summary> |
| | | 1933 | | /// Registers a route in the internal route registry. |
| | | 1934 | | /// </summary> |
| | | 1935 | | /// <param name="pattern">The route pattern.</param> |
| | | 1936 | | /// <param name="verb">The HTTP verb.</param> |
| | | 1937 | | /// <param name="routeOptions">The route options.</param> |
| | | 1938 | | private void RegisterRoute(string pattern, HttpVerb verb, MapRouteOptions routeOptions) |
| | 0 | 1939 | | => _registeredRoutes[(pattern, verb)] = routeOptions; |
| | | 1940 | | |
| | | 1941 | | /// <summary> |
| | | 1942 | | /// Ensures the default OpenAPI tags for real-time and SignalR are present when the caller uses default tagging. |
| | | 1943 | | /// </summary> |
| | | 1944 | | /// <param name="options">SignalR configuration options.</param> |
| | | 1945 | | /// <param name="apiDocDescriptors">OpenAPI document descriptors to update.</param> |
| | | 1946 | | private static void EnsureDefaultSignalRTags(SignalROptions options, IEnumerable<OpenApiDocDescriptor> apiDocDescrip |
| | | 1947 | | { |
| | 0 | 1948 | | if (options.Tags?.Contains(SignalROptions.DefaultTag) != true) |
| | | 1949 | | { |
| | 0 | 1950 | | return; |
| | | 1951 | | } |
| | | 1952 | | |
| | 0 | 1953 | | foreach (var defTag in apiDocDescriptors) |
| | | 1954 | | { |
| | 0 | 1955 | | AddRealTimeTag(defTag); |
| | 0 | 1956 | | AddSignalRTag(defTag); |
| | | 1957 | | } |
| | 0 | 1958 | | } |
| | | 1959 | | |
| | | 1960 | | /// <summary> |
| | | 1961 | | /// Creates the common OpenAPI response set for the SignalR hub connect endpoint. |
| | | 1962 | | /// </summary> |
| | | 1963 | | /// <returns>The OpenAPI responses collection.</returns> |
| | | 1964 | | private static OpenApiResponses CreateSignalRHubResponses() |
| | 0 | 1965 | | => new() |
| | 0 | 1966 | | { |
| | 0 | 1967 | | ["101"] = new OpenApiResponse { Description = "Switching Protocols (WebSocket upgrade)" }, |
| | 0 | 1968 | | ["401"] = new OpenApiResponse { Description = "Unauthorized" }, |
| | 0 | 1969 | | ["403"] = new OpenApiResponse { Description = "Forbidden" }, |
| | 0 | 1970 | | ["404"] = new OpenApiResponse { Description = "Not Found" }, |
| | 0 | 1971 | | ["500"] = new OpenApiResponse { Description = "Internal Server Error" } |
| | 0 | 1972 | | }; |
| | | 1973 | | |
| | | 1974 | | /// <summary> |
| | | 1975 | | /// Creates the common OpenAPI response set for the SignalR negotiate endpoint. |
| | | 1976 | | /// </summary> |
| | | 1977 | | /// <returns>The OpenAPI responses collection.</returns> |
| | | 1978 | | private static OpenApiResponses CreateSignalRNegotiateResponses() |
| | 0 | 1979 | | => new() |
| | 0 | 1980 | | { |
| | 0 | 1981 | | ["200"] = new OpenApiResponse { Description = "Successful negotiation" }, |
| | 0 | 1982 | | ["401"] = new OpenApiResponse { Description = "Unauthorized" }, |
| | 0 | 1983 | | ["403"] = new OpenApiResponse { Description = "Forbidden" }, |
| | 0 | 1984 | | ["404"] = new OpenApiResponse { Description = "Not Found" }, |
| | 0 | 1985 | | ["500"] = new OpenApiResponse { Description = "Internal Server Error" } |
| | 0 | 1986 | | }; |
| | | 1987 | | |
| | | 1988 | | /// <summary> |
| | | 1989 | | /// Builds the OpenAPI extensions for SignalR endpoints. |
| | | 1990 | | /// </summary> |
| | | 1991 | | /// <param name="options">SignalR configuration options.</param> |
| | | 1992 | | /// <param name="negotiatePath">The negotiate endpoint path.</param> |
| | | 1993 | | /// <param name="role">The SignalR endpoint role (e.g., connect, negotiate).</param> |
| | | 1994 | | /// <returns>Extensions dictionary for OpenAPI metadata.</returns> |
| | | 1995 | | private static Dictionary<string, IOpenApiExtension> CreateSignalRExtensions(SignalROptions options, string negotiat |
| | 0 | 1996 | | => new() |
| | 0 | 1997 | | { |
| | 0 | 1998 | | ["x-signalr-role"] = new JsonNodeExtension(JsonValue.Create(role)), |
| | 0 | 1999 | | ["x-signalr"] = new JsonNodeExtension(new JsonObject |
| | 0 | 2000 | | { |
| | 0 | 2001 | | ["hub"] = options.HubName, |
| | 0 | 2002 | | ["path"] = options.Path, |
| | 0 | 2003 | | ["negotiatePath"] = negotiatePath, |
| | 0 | 2004 | | ["connectOperation"] = "get:" + options.Path, |
| | 0 | 2005 | | ["transports"] = new JsonArray("websocket", "sse", "longPolling"), |
| | 0 | 2006 | | ["formats"] = new JsonArray("json"), |
| | 0 | 2007 | | }) |
| | 0 | 2008 | | }; |
| | | 2009 | | |
| | | 2010 | | /// <summary> |
| | | 2011 | | /// Adds OpenAPI metadata to the hub connect route, if OpenAPI is enabled. |
| | | 2012 | | /// </summary> |
| | | 2013 | | /// <param name="options">SignalR configuration options.</param> |
| | | 2014 | | /// <param name="apiDocDescriptors">OpenAPI document descriptors for tag registration.</param> |
| | | 2015 | | /// <param name="routeOptions">The route options to enrich with OpenAPI metadata.</param> |
| | | 2016 | | /// <param name="negotiatePath">The computed negotiate endpoint path.</param> |
| | | 2017 | | private void TryAddSignalRHubOpenApiMetadata( |
| | | 2018 | | SignalROptions options, |
| | | 2019 | | IEnumerable<OpenApiDocDescriptor> apiDocDescriptors, |
| | | 2020 | | MapRouteOptions routeOptions, |
| | | 2021 | | string negotiatePath) |
| | | 2022 | | { |
| | 0 | 2023 | | if (options.SkipOpenApi) |
| | | 2024 | | { |
| | 0 | 2025 | | return; |
| | | 2026 | | } |
| | | 2027 | | |
| | 0 | 2028 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2029 | | { |
| | 0 | 2030 | | Logger.Debug("Adding OpenAPI metadata for SignalR hub at path: {Path}", options.Path); |
| | | 2031 | | } |
| | | 2032 | | |
| | 0 | 2033 | | EnsureDefaultSignalRTags(options, apiDocDescriptors); |
| | | 2034 | | |
| | 0 | 2035 | | var meta = new OpenAPIPathMetadata(pattern: options.Path, mapOptions: routeOptions) |
| | 0 | 2036 | | { |
| | 0 | 2037 | | DocumentId = options.DocId, |
| | 0 | 2038 | | Summary = string.IsNullOrWhiteSpace(options.Summary) ? null : options.Summary, |
| | 0 | 2039 | | Description = string.IsNullOrWhiteSpace(options.Description) ? null : options.Description, |
| | 0 | 2040 | | Tags = options.Tags?.ToList() ?? [], |
| | 0 | 2041 | | Responses = CreateSignalRHubResponses(), |
| | 0 | 2042 | | Extensions = CreateSignalRExtensions(options, negotiatePath, role: "connect") |
| | 0 | 2043 | | }; |
| | | 2044 | | |
| | 0 | 2045 | | routeOptions.OpenAPI[HttpVerb.Get] = meta; |
| | 0 | 2046 | | } |
| | | 2047 | | |
| | | 2048 | | /// <summary> |
| | | 2049 | | /// Adds OpenAPI metadata to the negotiate route, if OpenAPI is enabled. |
| | | 2050 | | /// </summary> |
| | | 2051 | | /// <param name="options">SignalR configuration options.</param> |
| | | 2052 | | /// <param name="negotiateRouteOptions">The negotiate route options to enrich with OpenAPI metadata.</param> |
| | | 2053 | | /// <param name="negotiatePath">The negotiate endpoint path.</param> |
| | | 2054 | | private static void TryAddSignalRNegotiateOpenApiMetadata( |
| | | 2055 | | SignalROptions options, |
| | | 2056 | | MapRouteOptions negotiateRouteOptions, |
| | | 2057 | | string negotiatePath) |
| | | 2058 | | { |
| | 0 | 2059 | | if (options.SkipOpenApi) |
| | | 2060 | | { |
| | 0 | 2061 | | return; |
| | | 2062 | | } |
| | | 2063 | | |
| | 0 | 2064 | | var negotiateMeta = new OpenAPIPathMetadata(pattern: negotiatePath, mapOptions: negotiateRouteOptions) |
| | 0 | 2065 | | { |
| | 0 | 2066 | | Summary = "SignalR negotiate endpoint", |
| | 0 | 2067 | | Description = "Negotiates connection parameters for a SignalR client before establishing the transport.", |
| | 0 | 2068 | | Tags = options.Tags?.ToList() ?? [], |
| | 0 | 2069 | | Responses = CreateSignalRNegotiateResponses(), |
| | 0 | 2070 | | Extensions = CreateSignalRExtensions(options, negotiatePath, role: "negotiate") |
| | 0 | 2071 | | }; |
| | | 2072 | | |
| | 0 | 2073 | | negotiateRouteOptions.OpenAPI[HttpVerb.Post] = negotiateMeta; |
| | 0 | 2074 | | } |
| | | 2075 | | |
| | | 2076 | | /// <summary> |
| | | 2077 | | /// Registers SignalR services and JSON protocol configuration. |
| | | 2078 | | /// </summary> |
| | | 2079 | | /// <typeparam name="THub">The hub type being registered.</typeparam> |
| | | 2080 | | /// <param name="services">The service collection to configure.</param> |
| | | 2081 | | private static void ConfigureSignalRServices<THub>(IServiceCollection services) where THub : Hub |
| | | 2082 | | { |
| | 0 | 2083 | | _ = services.AddSignalR(o => |
| | 0 | 2084 | | { |
| | 0 | 2085 | | o.HandshakeTimeout = TimeSpan.FromSeconds(5); |
| | 0 | 2086 | | o.KeepAliveInterval = TimeSpan.FromSeconds(2); |
| | 0 | 2087 | | o.ClientTimeoutInterval = TimeSpan.FromSeconds(10); |
| | 0 | 2088 | | }).AddJsonProtocol(opts => |
| | 0 | 2089 | | { |
| | 0 | 2090 | | // Avoid failures when payloads contain cycles; our sanitizer should prevent most, this is a safety net. |
| | 0 | 2091 | | opts.PayloadSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; |
| | 0 | 2092 | | }); |
| | | 2093 | | |
| | | 2094 | | // Register IRealtimeBroadcaster as singleton if it's the KestrunHub |
| | 0 | 2095 | | if (typeof(THub) == typeof(SignalR.KestrunHub)) |
| | | 2096 | | { |
| | 0 | 2097 | | _ = services.AddSingleton<SignalR.IRealtimeBroadcaster, SignalR.RealtimeBroadcaster>(); |
| | 0 | 2098 | | _ = services.AddSingleton<SignalR.IConnectionTracker, SignalR.InMemoryConnectionTracker>(); |
| | | 2099 | | } |
| | 0 | 2100 | | } |
| | | 2101 | | |
| | | 2102 | | /// <summary> |
| | | 2103 | | /// Maps the SignalR hub to the application's endpoint route builder. |
| | | 2104 | | /// </summary> |
| | | 2105 | | /// <typeparam name="THub">The hub type being mapped.</typeparam> |
| | | 2106 | | /// <param name="app">The application builder.</param> |
| | | 2107 | | /// <param name="path">The hub path.</param> |
| | | 2108 | | private static void MapSignalRHub<THub>(IApplicationBuilder app, string path) where THub : Hub |
| | 0 | 2109 | | => ((IEndpointRouteBuilder)app).MapHub<THub>(path); |
| | | 2110 | | |
| | | 2111 | | /// <summary> |
| | | 2112 | | /// Adds a SignalR hub to the application at the specified path. |
| | | 2113 | | /// </summary> |
| | | 2114 | | /// <typeparam name="T">The type of the SignalR hub.</typeparam> |
| | | 2115 | | /// <param name="options">The options for configuring the SignalR hub.</param> |
| | | 2116 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 2117 | | public KestrunHost AddSignalR<T>(SignalROptions options) where T : Hub |
| | | 2118 | | { |
| | 0 | 2119 | | options ??= SignalROptions.Default; |
| | | 2120 | | |
| | 0 | 2121 | | var apiDocDescriptors = GetOrCreateOpenApiDocument(options.DocId); |
| | 0 | 2122 | | var negotiatePath = GetSignalRNegotiatePath(options.Path); |
| | | 2123 | | |
| | 0 | 2124 | | var routeOptions = CreateNativeRouteOptions(options.Path, HttpVerb.Get); |
| | 0 | 2125 | | TryAddSignalRHubOpenApiMetadata(options, apiDocDescriptors, routeOptions, negotiatePath); |
| | 0 | 2126 | | RegisterRoute(options.Path, HttpVerb.Get, routeOptions); |
| | | 2127 | | |
| | 0 | 2128 | | if (options.IncludeNegotiateEndpoint) |
| | | 2129 | | { |
| | 0 | 2130 | | var negotiateRouteOptions = CreateNativeRouteOptions(negotiatePath, HttpVerb.Post); |
| | 0 | 2131 | | TryAddSignalRNegotiateOpenApiMetadata(options, negotiateRouteOptions, negotiatePath); |
| | 0 | 2132 | | RegisterRoute(negotiatePath, HttpVerb.Post, negotiateRouteOptions); |
| | | 2133 | | } |
| | | 2134 | | |
| | 0 | 2135 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2136 | | { |
| | 0 | 2137 | | Logger.Debug("Adding SignalR hub of type {HubType} at path: {Path}", typeof(T).FullName, options.Path); |
| | | 2138 | | } |
| | | 2139 | | |
| | 0 | 2140 | | return AddService(ConfigureSignalRServices<T>) |
| | 0 | 2141 | | .Use(app => MapSignalRHub<T>(app, options.Path)); |
| | | 2142 | | } |
| | | 2143 | | |
| | | 2144 | | /// <summary> |
| | | 2145 | | /// Adds the default SignalR hub (KestrunHub) to the application at the specified path. |
| | | 2146 | | /// </summary> |
| | | 2147 | | /// <param name="options">The options for configuring the SignalR hub.</param> |
| | | 2148 | | /// <returns></returns> |
| | 0 | 2149 | | public KestrunHost AddSignalR(SignalROptions options) => AddSignalR<SignalR.KestrunHub>(options); |
| | | 2150 | | |
| | | 2151 | | /* |
| | | 2152 | | // ④ gRPC |
| | | 2153 | | public KestrunHost AddGrpc<TService>() where TService : class |
| | | 2154 | | { |
| | | 2155 | | return AddService(s => s.AddGrpc()) |
| | | 2156 | | .Use(app => app.MapGrpcService<TService>()); |
| | | 2157 | | } |
| | | 2158 | | */ |
| | | 2159 | | |
| | | 2160 | | // Add as many tiny helpers as you wish: |
| | | 2161 | | // • AddAuthentication(jwt => { … }) |
| | | 2162 | | // • AddSignalR() |
| | | 2163 | | // • AddHealthChecks() |
| | | 2164 | | // • AddGrpc() |
| | | 2165 | | // etc. |
| | | 2166 | | |
| | | 2167 | | #endregion |
| | | 2168 | | #region Run/Start/Stop |
| | | 2169 | | |
| | | 2170 | | /// <summary> |
| | | 2171 | | /// Runs the Kestrun web application, applying configuration and starting the server. |
| | | 2172 | | /// </summary> |
| | | 2173 | | public void Run() |
| | | 2174 | | { |
| | 0 | 2175 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2176 | | { |
| | 0 | 2177 | | Logger.Debug("Run() called"); |
| | | 2178 | | } |
| | | 2179 | | |
| | 0 | 2180 | | EnableConfiguration(); |
| | 0 | 2181 | | Runtime.StartTime = DateTime.UtcNow; |
| | 0 | 2182 | | _app?.Run(); |
| | 0 | 2183 | | } |
| | | 2184 | | |
| | | 2185 | | /// <summary> |
| | | 2186 | | /// Starts the Kestrun web application asynchronously. |
| | | 2187 | | /// </summary> |
| | | 2188 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> |
| | | 2189 | | /// <returns>A task that represents the asynchronous start operation.</returns> |
| | | 2190 | | public async Task StartAsync(CancellationToken cancellationToken = default) |
| | | 2191 | | { |
| | 21 | 2192 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2193 | | { |
| | 1 | 2194 | | Logger.Debug("StartAsync() called"); |
| | | 2195 | | } |
| | | 2196 | | |
| | 21 | 2197 | | EnableConfiguration(); |
| | 21 | 2198 | | if (_app != null) |
| | | 2199 | | { |
| | 21 | 2200 | | Runtime.StartTime = DateTime.UtcNow; |
| | 21 | 2201 | | await _app.StartAsync(cancellationToken); |
| | | 2202 | | } |
| | 21 | 2203 | | } |
| | | 2204 | | |
| | | 2205 | | /// <summary> |
| | | 2206 | | /// Stops the Kestrun web application asynchronously. |
| | | 2207 | | /// </summary> |
| | | 2208 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param> |
| | | 2209 | | /// <returns>A task that represents the asynchronous stop operation.</returns> |
| | | 2210 | | public async Task StopAsync(CancellationToken cancellationToken = default) |
| | | 2211 | | { |
| | 26 | 2212 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2213 | | { |
| | 6 | 2214 | | Logger.Debug("StopAsync() called"); |
| | | 2215 | | } |
| | | 2216 | | |
| | 26 | 2217 | | if (_app != null) |
| | | 2218 | | { |
| | | 2219 | | try |
| | | 2220 | | { |
| | | 2221 | | // Initiate graceful shutdown |
| | 21 | 2222 | | await _app.StopAsync(cancellationToken); |
| | 21 | 2223 | | Runtime.StopTime = DateTime.UtcNow; |
| | 21 | 2224 | | } |
| | 0 | 2225 | | catch (Exception ex) when (ex.GetType().FullName == "System.Net.Quic.QuicException") |
| | | 2226 | | { |
| | | 2227 | | // QUIC exceptions can occur during shutdown, especially if the server is not using QUIC. |
| | | 2228 | | // We log this as a debug message to avoid cluttering the logs with expected exceptions. |
| | | 2229 | | // This is a workaround for |
| | | 2230 | | |
| | 0 | 2231 | | Logger.Debug("Ignored QUIC exception during shutdown: {Message}", ex.Message); |
| | 0 | 2232 | | } |
| | | 2233 | | } |
| | 26 | 2234 | | } |
| | | 2235 | | |
| | | 2236 | | /// <summary> |
| | | 2237 | | /// Initiates a graceful shutdown of the Kestrun web application. |
| | | 2238 | | /// </summary> |
| | | 2239 | | public void Stop() |
| | | 2240 | | { |
| | 1 | 2241 | | if (Interlocked.Exchange(ref _stopping, 1) == 1) |
| | | 2242 | | { |
| | 0 | 2243 | | return; // already stopping |
| | | 2244 | | } |
| | 1 | 2245 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2246 | | { |
| | 1 | 2247 | | Logger.Debug("Stop() called"); |
| | | 2248 | | } |
| | | 2249 | | // This initiates a graceful shutdown. |
| | 1 | 2250 | | _app?.Lifetime.StopApplication(); |
| | 1 | 2251 | | Runtime.StopTime = DateTime.UtcNow; |
| | 1 | 2252 | | } |
| | | 2253 | | |
| | | 2254 | | /// <summary> |
| | | 2255 | | /// Determines whether the Kestrun web application is currently running. |
| | | 2256 | | /// </summary> |
| | | 2257 | | /// <returns>True if the application is running; otherwise, false.</returns> |
| | | 2258 | | public bool IsRunning |
| | | 2259 | | { |
| | | 2260 | | get |
| | | 2261 | | { |
| | 8 | 2262 | | var appField = typeof(KestrunHost) |
| | 8 | 2263 | | .GetField("_app", BindingFlags.NonPublic | BindingFlags.Instance); |
| | | 2264 | | |
| | 8 | 2265 | | return appField?.GetValue(this) is WebApplication app && !app.Lifetime.ApplicationStopping.IsCancellationReq |
| | | 2266 | | } |
| | | 2267 | | } |
| | | 2268 | | |
| | | 2269 | | #endregion |
| | | 2270 | | |
| | | 2271 | | #region Runspace Pool Management |
| | | 2272 | | |
| | | 2273 | | /// <summary> |
| | | 2274 | | /// Creates and returns a new <see cref="KestrunRunspacePoolManager"/> instance with the specified maximum number of |
| | | 2275 | | /// </summary> |
| | | 2276 | | /// <param name="maxRunspaces">The maximum number of runspaces to create. If not specified or zero, defaults to twic |
| | | 2277 | | /// <param name="userVariables">A dictionary of user-defined variables to inject into the runspace pool.</param> |
| | | 2278 | | /// <param name="userFunctions">A dictionary of user-defined functions to inject into the runspace pool.</param> |
| | | 2279 | | /// <param name="openApiClassesPath">The file path to the OpenAPI class definitions to inject into the runspace pool |
| | | 2280 | | /// <returns>A configured <see cref="KestrunRunspacePoolManager"/> instance.</returns> |
| | | 2281 | | public KestrunRunspacePoolManager CreateRunspacePool(int? maxRunspaces = 0, Dictionary<string, object>? userVariable |
| | | 2282 | | { |
| | 69 | 2283 | | LogCreateRunspacePool(maxRunspaces); |
| | | 2284 | | |
| | 69 | 2285 | | var iss = BuildInitialSessionState(openApiClassesPath); |
| | 69 | 2286 | | AddHostVariables(iss); |
| | 69 | 2287 | | AddSharedVariables(iss); |
| | 69 | 2288 | | AddUserVariables(iss, userVariables); |
| | 69 | 2289 | | AddUserFunctions(iss, userFunctions); |
| | | 2290 | | |
| | 69 | 2291 | | var maxRs = ResolveMaxRunspaces(maxRunspaces); |
| | | 2292 | | |
| | 69 | 2293 | | Logger.Information("Creating runspace pool with max runspaces: {MaxRunspaces}", maxRs); |
| | 69 | 2294 | | return new KestrunRunspacePoolManager(this, Options?.MinRunspaces ?? 1, maxRunspaces: maxRs, initialSessionState |
| | | 2295 | | } |
| | | 2296 | | |
| | | 2297 | | private void LogCreateRunspacePool(int? maxRunspaces) |
| | | 2298 | | { |
| | 69 | 2299 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2300 | | { |
| | 46 | 2301 | | Logger.Debug("CreateRunspacePool() called: {@MaxRunspaces}", maxRunspaces); |
| | | 2302 | | } |
| | 69 | 2303 | | } |
| | | 2304 | | |
| | | 2305 | | private InitialSessionState BuildInitialSessionState(string? openApiClassesPath) |
| | | 2306 | | { |
| | 69 | 2307 | | var iss = InitialSessionState.CreateDefault(); |
| | | 2308 | | |
| | 69 | 2309 | | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| | | 2310 | | { |
| | | 2311 | | // On Windows, we can use the full .NET Framework modules |
| | 0 | 2312 | | iss.ExecutionPolicy = ExecutionPolicy.Unrestricted; |
| | | 2313 | | } |
| | | 2314 | | |
| | 69 | 2315 | | ImportModulePaths(iss); |
| | 69 | 2316 | | AddOpenApiStartupScript(iss, openApiClassesPath); |
| | | 2317 | | |
| | 69 | 2318 | | return iss; |
| | | 2319 | | } |
| | | 2320 | | |
| | | 2321 | | private void ImportModulePaths(InitialSessionState iss) |
| | | 2322 | | { |
| | 276 | 2323 | | foreach (var path in _modulePaths) |
| | | 2324 | | { |
| | 69 | 2325 | | iss.ImportPSModule([path]); |
| | | 2326 | | } |
| | 69 | 2327 | | } |
| | | 2328 | | |
| | | 2329 | | private void AddOpenApiStartupScript(InitialSessionState iss, string? openApiClassesPath) |
| | | 2330 | | { |
| | 69 | 2331 | | if (string.IsNullOrWhiteSpace(openApiClassesPath)) |
| | | 2332 | | { |
| | 68 | 2333 | | return; |
| | | 2334 | | } |
| | | 2335 | | |
| | 1 | 2336 | | _ = iss.StartupScripts.Add(openApiClassesPath); |
| | 1 | 2337 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2338 | | { |
| | 1 | 2339 | | Logger.Debug("Configured OpenAPI class script at {ScriptPath}", openApiClassesPath); |
| | | 2340 | | } |
| | 1 | 2341 | | } |
| | | 2342 | | |
| | | 2343 | | private void AddHostVariables(InitialSessionState iss) |
| | | 2344 | | { |
| | 69 | 2345 | | iss.Variables.Add( |
| | 69 | 2346 | | new SessionStateVariableEntry( |
| | 69 | 2347 | | "KrServer", |
| | 69 | 2348 | | this, |
| | 69 | 2349 | | "The Kestrun Server Host (KestrunHost) instance" |
| | 69 | 2350 | | ) |
| | 69 | 2351 | | ); |
| | 69 | 2352 | | } |
| | | 2353 | | |
| | | 2354 | | private void AddSharedVariables(InitialSessionState iss) |
| | | 2355 | | { |
| | 140 | 2356 | | foreach (var kvp in SharedState.Snapshot()) |
| | | 2357 | | { |
| | 1 | 2358 | | iss.Variables.Add( |
| | 1 | 2359 | | new SessionStateVariableEntry( |
| | 1 | 2360 | | kvp.Key, |
| | 1 | 2361 | | kvp.Value, |
| | 1 | 2362 | | "Global variable" |
| | 1 | 2363 | | ) |
| | 1 | 2364 | | ); |
| | | 2365 | | } |
| | 69 | 2366 | | } |
| | | 2367 | | |
| | | 2368 | | private static void AddUserVariables(InitialSessionState iss, IReadOnlyDictionary<string, object>? userVariables) |
| | | 2369 | | { |
| | 69 | 2370 | | if (userVariables is null) |
| | | 2371 | | { |
| | 67 | 2372 | | return; |
| | | 2373 | | } |
| | | 2374 | | |
| | 10 | 2375 | | foreach (var kvp in userVariables) |
| | | 2376 | | { |
| | 3 | 2377 | | if (kvp.Value is PSVariable psVar) |
| | | 2378 | | { |
| | 1 | 2379 | | iss.Variables.Add( |
| | 1 | 2380 | | new SessionStateVariableEntry( |
| | 1 | 2381 | | kvp.Key, |
| | 1 | 2382 | | UnwrapKestrunVariableValue(psVar.Value), |
| | 1 | 2383 | | psVar.Description ?? "User-defined variable" |
| | 1 | 2384 | | ) |
| | 1 | 2385 | | ); |
| | 1 | 2386 | | continue; |
| | | 2387 | | } |
| | | 2388 | | |
| | 2 | 2389 | | iss.Variables.Add( |
| | 2 | 2390 | | new SessionStateVariableEntry( |
| | 2 | 2391 | | kvp.Key, |
| | 2 | 2392 | | UnwrapKestrunVariableValue(kvp.Value), |
| | 2 | 2393 | | "User-defined variable" |
| | 2 | 2394 | | ) |
| | 2 | 2395 | | ); |
| | | 2396 | | } |
| | 2 | 2397 | | } |
| | | 2398 | | |
| | | 2399 | | /// <summary> |
| | | 2400 | | /// Unwraps a Kestrun variable value if it is wrapped in a dictionary with a specific marker. |
| | | 2401 | | /// </summary> |
| | | 2402 | | /// <param name="raw">The raw variable value to unwrap.</param> |
| | | 2403 | | /// <returns>The unwrapped variable value, or the original value if not wrapped.</returns> |
| | | 2404 | | private static object? UnwrapKestrunVariableValue(object? raw) |
| | | 2405 | | { |
| | 3 | 2406 | | if (raw is null) |
| | | 2407 | | { |
| | 0 | 2408 | | return null; |
| | | 2409 | | } |
| | | 2410 | | |
| | | 2411 | | // unwrap PSObject if needed |
| | 3 | 2412 | | raw = UnwrapPsObject(raw); |
| | | 2413 | | |
| | | 2414 | | // check for dictionary |
| | 3 | 2415 | | if (raw is not System.Collections.IDictionary dict) |
| | | 2416 | | { |
| | 3 | 2417 | | return raw; |
| | | 2418 | | } |
| | | 2419 | | |
| | | 2420 | | // check for marker key |
| | 0 | 2421 | | if (!TryGetDictionaryValueIgnoreCase(dict, KestrunVariableMarkerKey, out var markerObj)) |
| | | 2422 | | { |
| | 0 | 2423 | | return raw; |
| | | 2424 | | } |
| | | 2425 | | |
| | | 2426 | | // check if marker is enabled |
| | 0 | 2427 | | if (!IsKestrunVariableMarkerEnabled(markerObj)) |
| | | 2428 | | { |
| | 0 | 2429 | | return raw; |
| | | 2430 | | } |
| | | 2431 | | |
| | | 2432 | | // extract the "Value" entry |
| | 0 | 2433 | | return TryGetDictionaryValueIgnoreCase(dict, "Value", out var valueObj) |
| | 0 | 2434 | | ? UnwrapPsObject(valueObj) |
| | 0 | 2435 | | : null; |
| | | 2436 | | } |
| | | 2437 | | |
| | | 2438 | | /// <summary> |
| | | 2439 | | /// Unwraps a PowerShell <see cref="PSObject"/> by returning its <see cref="PSObject.BaseObject"/>. |
| | | 2440 | | /// </summary> |
| | | 2441 | | /// <param name="raw">The value to unwrap.</param> |
| | | 2442 | | /// <returns>The underlying base object when <paramref name="raw"/> is a <see cref="PSObject"/>, otherwise <paramref |
| | | 2443 | | private static object? UnwrapPsObject(object? raw) |
| | 3 | 2444 | | => raw is PSObject pso ? pso.BaseObject : raw; |
| | | 2445 | | |
| | | 2446 | | /// <summary> |
| | | 2447 | | /// Determines whether the Kestrun variable marker is enabled. |
| | | 2448 | | /// </summary> |
| | | 2449 | | /// <param name="markerObj">The marker value (typically a boolean or a PowerShell-wrapped boolean).</param> |
| | | 2450 | | /// <returns><c>true</c> if the marker indicates the value is wrapped; otherwise, <c>false</c>.</returns> |
| | | 2451 | | private static bool IsKestrunVariableMarkerEnabled(object? markerObj) |
| | 0 | 2452 | | => markerObj switch |
| | 0 | 2453 | | { |
| | 0 | 2454 | | bool b => b, |
| | 0 | 2455 | | PSObject psMarker when psMarker.BaseObject is bool b => b, |
| | 0 | 2456 | | _ => false |
| | 0 | 2457 | | }; |
| | | 2458 | | |
| | | 2459 | | private static bool TryGetDictionaryValueIgnoreCase(System.Collections.IDictionary dict, string key, out object? val |
| | | 2460 | | { |
| | 0 | 2461 | | value = null; |
| | | 2462 | | |
| | 0 | 2463 | | if (dict.Contains(key)) |
| | | 2464 | | { |
| | 0 | 2465 | | value = dict[key]; |
| | 0 | 2466 | | return true; |
| | | 2467 | | } |
| | | 2468 | | |
| | 0 | 2469 | | foreach (System.Collections.DictionaryEntry de in dict) |
| | | 2470 | | { |
| | 0 | 2471 | | if (de.Key is string s && string.Equals(s, key, StringComparison.OrdinalIgnoreCase)) |
| | | 2472 | | { |
| | 0 | 2473 | | value = de.Value; |
| | 0 | 2474 | | return true; |
| | | 2475 | | } |
| | | 2476 | | } |
| | | 2477 | | |
| | 0 | 2478 | | return false; |
| | 0 | 2479 | | } |
| | | 2480 | | |
| | | 2481 | | private static void AddUserFunctions(InitialSessionState iss, IReadOnlyDictionary<string, string>? userFunctions) |
| | | 2482 | | { |
| | 69 | 2483 | | if (userFunctions is null) |
| | | 2484 | | { |
| | 66 | 2485 | | return; |
| | | 2486 | | } |
| | | 2487 | | |
| | 12 | 2488 | | foreach (var function in userFunctions) |
| | | 2489 | | { |
| | 3 | 2490 | | var entry = new SessionStateFunctionEntry( |
| | 3 | 2491 | | function.Key, |
| | 3 | 2492 | | function.Value, |
| | 3 | 2493 | | ScopedItemOptions.ReadOnly, |
| | 3 | 2494 | | helpFile: null |
| | 3 | 2495 | | ); |
| | | 2496 | | |
| | 3 | 2497 | | iss.Commands.Add(entry); |
| | | 2498 | | } |
| | 3 | 2499 | | } |
| | | 2500 | | |
| | | 2501 | | private static int ResolveMaxRunspaces(int? maxRunspaces) => |
| | 69 | 2502 | | (maxRunspaces.HasValue && maxRunspaces.Value > 0) |
| | 69 | 2503 | | ? maxRunspaces.Value |
| | 69 | 2504 | | : Environment.ProcessorCount * 2; |
| | | 2505 | | |
| | | 2506 | | #endregion |
| | | 2507 | | |
| | | 2508 | | #region Disposable |
| | | 2509 | | |
| | | 2510 | | /// <summary> |
| | | 2511 | | /// Releases all resources used by the <see cref="KestrunHost"/> instance. |
| | | 2512 | | /// </summary> |
| | | 2513 | | public void Dispose() |
| | | 2514 | | { |
| | 274 | 2515 | | if (Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 2516 | | { |
| | 267 | 2517 | | Logger.Debug("Dispose() called"); |
| | | 2518 | | } |
| | | 2519 | | |
| | 274 | 2520 | | _runspacePool?.Dispose(); |
| | 274 | 2521 | | _runspacePool = null; // Clear the runspace pool reference |
| | 274 | 2522 | | IsConfigured = false; // Reset configuration state |
| | 274 | 2523 | | _app = null; |
| | 274 | 2524 | | _scheduler?.Dispose(); |
| | 274 | 2525 | | (Logger as IDisposable)?.Dispose(); |
| | 274 | 2526 | | GC.SuppressFinalize(this); |
| | 274 | 2527 | | } |
| | | 2528 | | #endregion |
| | | 2529 | | |
| | | 2530 | | #region Script Validation |
| | | 2531 | | |
| | | 2532 | | #endregion |
| | | 2533 | | } |