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