| | 1 | | using System.Management.Automation; |
| | 2 | | using Kestrun.Scripting; |
| | 3 | | using Kestrun.Utilities; |
| | 4 | | using Serilog; |
| | 5 | | using Serilog.Events; |
| | 6 | |
|
| | 7 | | namespace Kestrun.Razor; |
| | 8 | |
|
| | 9 | | /// <summary> |
| | 10 | | /// Provides middleware for enabling PowerShell-backed Razor Pages, allowing execution of a sibling PowerShell script (* |
| | 11 | | /// </summary> |
| | 12 | | /// <remarks> |
| | 13 | | /// This middleware allows for dynamic content generation in Razor Pages by leveraging PowerShell scripts. |
| | 14 | | /// Middleware that lets any Razor view (*.cshtml) load a sibling PowerShell |
| | 15 | | /// script (*.cshtml.ps1) in the SAME request. The script can set `$Model` which |
| | 16 | | /// then becomes available to the Razor page through HttpContext.Items. |
| | 17 | | /// ----------------------------------------------------------------------------- |
| | 18 | | /// |
| | 19 | | /// Usage (inside KestrunHost.ApplyConfiguration): |
| | 20 | | /// builder.Services.AddRazorPages(); // already present |
| | 21 | | /// … |
| | 22 | | /// /* AFTER you build App and create _runspacePool: */ |
| | 23 | | /// |
| | 24 | | /// App.UsePowerShellRazorPages(_runspacePool); |
| | 25 | | /// |
| | 26 | | /// That’s it – no per-page registration. |
| | 27 | | /// </remarks> |
| | 28 | | public static class PowerShellRazorPage |
| | 29 | | { |
| | 30 | | private const string MODEL_KEY = "PageModel"; |
| | 31 | |
|
| | 32 | | /// <summary> |
| | 33 | | /// Enables <c>.cshtml</c> + <c>.cshtml.ps1</c> pairs. |
| | 34 | | /// For a request to <c>/Foo</c> it will, in order: |
| | 35 | | /// <list type="number"> |
| | 36 | | /// <item><description>Look for <c>Pages/Foo.cshtml</c></description></item> |
| | 37 | | /// <item><description>If a <c>Pages/Foo.cshtml.ps1</c> exists, execute it |
| | 38 | | /// in the supplied runspace-pool</description></item> |
| | 39 | | /// <item><description>Whatever the script assigns to <c>$Model</c> |
| | 40 | | /// is copied to <c>HttpContext.Items["PageModel"]</c></description></item> |
| | 41 | | /// </list> |
| | 42 | | /// Razor pages (or a generic <see cref="PwshKestrunModel"/>) can then |
| | 43 | | /// read that dynamic object. |
| | 44 | | /// </summary> |
| | 45 | | /// <param name="app">The <see cref="WebApplication"/> pipeline.</param> |
| | 46 | | /// <param name="pool">Kestrun’s shared <see cref="KestrunRunspacePoolManager"/>.</param> |
| | 47 | | /// <returns><paramref name="app"/> for fluent chaining.</returns> |
| | 48 | | public static IApplicationBuilder UsePowerShellRazorPages( |
| | 49 | | this IApplicationBuilder app, |
| | 50 | | KestrunRunspacePoolManager pool) |
| | 51 | | { |
| 2 | 52 | | ArgumentNullException.ThrowIfNull(app); |
| 2 | 53 | | ArgumentNullException.ThrowIfNull(pool); |
| | 54 | |
|
| 2 | 55 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 56 | | { |
| 2 | 57 | | Log.Debug("Configuring PowerShell Razor Pages middleware"); |
| | 58 | | } |
| | 59 | |
|
| 2 | 60 | | var env = app.ApplicationServices.GetRequiredService<IHostEnvironment>(); |
| 2 | 61 | | var pagesRoot = Path.Combine(env.ContentRootPath, "Pages"); |
| 2 | 62 | | Log.Information("Using Pages directory: {Path}", pagesRoot); |
| 2 | 63 | | if (!Directory.Exists(pagesRoot)) |
| | 64 | | { |
| 0 | 65 | | Log.Warning("Pages directory not found: {Path}", pagesRoot); |
| | 66 | | } |
| | 67 | |
|
| | 68 | | // MUST run before MapRazorPages() |
| 2 | 69 | | _ = app.Use(async (context, next) => |
| 2 | 70 | | { |
| 2 | 71 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| 2 | 72 | | { |
| 2 | 73 | | Log.Debug("Processing PowerShell Razor Page request for {Path}", context.Request.Path); |
| 2 | 74 | | } |
| 2 | 75 | |
|
| 2 | 76 | | var relPath = GetRelativePath(context); |
| 2 | 77 | | if (relPath is null) |
| 2 | 78 | | { |
| 0 | 79 | | await next(); |
| 0 | 80 | | return; |
| 2 | 81 | | } |
| 2 | 82 | |
|
| 2 | 83 | | var (view, psfile, csfile) = BuildCandidatePaths(pagesRoot, relPath); |
| 2 | 84 | | if (HasCodeBehind(csfile)) |
| 2 | 85 | | { |
| 0 | 86 | | await next(); |
| 0 | 87 | | return; |
| 2 | 88 | | } |
| 2 | 89 | |
|
| 2 | 90 | | if (!FilesExist(view, psfile)) |
| 2 | 91 | | { |
| 0 | 92 | | await next(); |
| 0 | 93 | | return; |
| 2 | 94 | | } |
| 2 | 95 | |
|
| 2 | 96 | | PowerShell? ps = null; |
| 2 | 97 | | try |
| 2 | 98 | | { |
| 2 | 99 | | ps = CreatePowerShell(pool); |
| 2 | 100 | | PrepareSession(ps, context); |
| 2 | 101 | | await AddScriptFromFileAsync(ps, psfile, context.RequestAborted); |
| 2 | 102 | | LogExecution(psfile); |
| 2 | 103 | | var psResults = await InvokePowerShellAsync(ps).ConfigureAwait(false); |
| 2 | 104 | | LogResultsCount(psResults.Count); |
| 2 | 105 | |
|
| 2 | 106 | | SetModelIfPresent(ps, context); |
| 2 | 107 | |
|
| 2 | 108 | | if (HasErrors(ps)) |
| 2 | 109 | | { |
| 1 | 110 | | await HandleErrorsAsync(context, ps); |
| 1 | 111 | | return; |
| 2 | 112 | | } |
| 2 | 113 | |
|
| 1 | 114 | | LogStreamsIfAny(ps); |
| 2 | 115 | |
|
| 1 | 116 | | await next(); // continue the pipeline |
| 1 | 117 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| 2 | 118 | | { |
| 1 | 119 | | Log.Debug("PowerShell Razor Page completed for {Path}", context.Request.Path); |
| 2 | 120 | | } |
| 1 | 121 | | } |
| 0 | 122 | | catch (Exception ex) |
| 2 | 123 | | { |
| 0 | 124 | | Log.Error(ex, "Error occurred in PowerShell Razor Page middleware for {Path}", context.Request.Path); |
| 0 | 125 | | } |
| 2 | 126 | | finally |
| 2 | 127 | | { |
| 2 | 128 | | ReturnRunspaceAndDispose(ps, pool); |
| 2 | 129 | | } |
| 4 | 130 | | }); |
| | 131 | |
|
| | 132 | | // static files & routing can be added earlier in pipeline |
| | 133 | |
|
| 2 | 134 | | _ = app.UseRouting(); |
| 4 | 135 | | _ = app.UseEndpoints(e => e.MapRazorPages()); |
| 2 | 136 | | return app; |
| | 137 | | } |
| | 138 | | /// <summary> |
| | 139 | | /// Gets the relative path for the PowerShell Razor Page from the HTTP context. |
| | 140 | | /// </summary> |
| | 141 | | /// <param name="context">The HTTP context.</param> |
| | 142 | | /// <returns>The relative path for the PowerShell Razor Page.</returns> |
| | 143 | | private static string? GetRelativePath(HttpContext context) |
| | 144 | | { |
| 2 | 145 | | var relPath = context.Request.Path.Value?.Trim('/'); |
| 2 | 146 | | if (string.IsNullOrEmpty(relPath)) |
| | 147 | | { |
| 0 | 148 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 149 | | { |
| 0 | 150 | | Log.Debug("Request path is empty, skipping PowerShell Razor Page processing"); |
| | 151 | | } |
| | 152 | |
|
| 0 | 153 | | return null; |
| | 154 | | } |
| 2 | 155 | | relPath = relPath.Replace('/', Path.DirectorySeparatorChar); |
| 2 | 156 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 157 | | { |
| 2 | 158 | | Log.Debug("Transformed request path to relative: {RelPath}", relPath); |
| | 159 | | } |
| | 160 | |
|
| 2 | 161 | | return relPath; |
| | 162 | | } |
| | 163 | |
|
| | 164 | | /// <summary> |
| | 165 | | /// Builds the candidate file paths for a PowerShell Razor Page. |
| | 166 | | /// </summary> |
| | 167 | | /// <param name="pagesRoot">The root directory for the Razor Pages.</param> |
| | 168 | | /// <param name="relPath">The relative path for the Razor Page.</param> |
| | 169 | | /// <returns>The candidate file paths for the Razor Page.</returns> |
| | 170 | | private static (string view, string psfile, string csfile) BuildCandidatePaths(string pagesRoot, string relPath) |
| | 171 | | { |
| 2 | 172 | | var view = Path.Combine(pagesRoot, relPath + ".cshtml"); |
| 2 | 173 | | var psfile = view + ".ps1"; |
| 2 | 174 | | var csfile = view + ".cs"; |
| 2 | 175 | | return (view, psfile, csfile); |
| | 176 | | } |
| | 177 | |
|
| | 178 | | /// <summary> |
| | 179 | | /// Checks if the C# code-behind file exists. |
| | 180 | | /// </summary> |
| | 181 | | /// <param name="csfile">The path to the C# code-behind file.</param> |
| | 182 | | /// <returns>True if the code-behind file exists; otherwise, false.</returns> |
| | 183 | | private static bool HasCodeBehind(string csfile) |
| | 184 | | { |
| 2 | 185 | | if (File.Exists(csfile)) |
| | 186 | | { |
| 0 | 187 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 188 | | { |
| 0 | 189 | | Log.Debug("Found C# code-behind file: {CsFile}", csfile); |
| | 190 | | } |
| | 191 | |
|
| 0 | 192 | | return true; |
| | 193 | | } |
| 2 | 194 | | return false; |
| | 195 | | } |
| | 196 | |
|
| | 197 | | /// <summary> |
| | 198 | | /// Checks if the PowerShell Razor Page files exist. |
| | 199 | | /// </summary> |
| | 200 | | /// <param name="view">The path to the Razor view file.</param> |
| | 201 | | /// <param name="psfile">The path to the PowerShell script file.</param> |
| | 202 | | /// <returns>True if the files exist; otherwise, false.</returns> |
| | 203 | | private static bool FilesExist(string view, string psfile) |
| | 204 | | { |
| 2 | 205 | | var ok = File.Exists(view) && File.Exists(psfile); |
| 2 | 206 | | if (!ok && Log.IsEnabled(LogEventLevel.Debug)) |
| | 207 | | { |
| 0 | 208 | | Log.Debug("PowerShell Razor Page files not found: {View} or {PsFile}", view, psfile); |
| | 209 | | } |
| | 210 | |
|
| 2 | 211 | | return ok; |
| | 212 | | } |
| | 213 | |
|
| | 214 | | /// <summary> |
| | 215 | | /// Creates a PowerShell instance from the runspace pool. |
| | 216 | | /// </summary> |
| | 217 | | /// <param name="pool">The runspace pool manager.</param> |
| | 218 | | /// <returns>The PowerShell instance.</returns> |
| | 219 | | private static PowerShell CreatePowerShell(KestrunRunspacePoolManager pool) |
| 2 | 220 | | => PowerShell.Create(pool.Acquire()); |
| | 221 | |
|
| | 222 | | /// <summary> |
| | 223 | | /// Prepares the PowerShell session with the HTTP context. |
| | 224 | | /// </summary> |
| | 225 | | /// <param name="ps">The PowerShell instance.</param> |
| | 226 | | /// <param name="context">The HTTP context.</param> |
| | 227 | | private static void PrepareSession(PowerShell ps, HttpContext context) |
| | 228 | | { |
| 2 | 229 | | var ss = ps.Runspace.SessionStateProxy; |
| 2 | 230 | | ss.SetVariable("Context", context); |
| 2 | 231 | | ss.SetVariable("Model", null); |
| 2 | 232 | | } |
| | 233 | |
|
| | 234 | | /// <summary> |
| | 235 | | /// Adds a PowerShell script from a file to the PowerShell instance. |
| | 236 | | /// </summary> |
| | 237 | | /// <param name="ps">The PowerShell instance.</param> |
| | 238 | | /// <param name="path">The path to the script file.</param> |
| | 239 | | /// <param name="token">The cancellation token.</param> |
| | 240 | | private static async Task AddScriptFromFileAsync(PowerShell ps, string path, CancellationToken token) |
| | 241 | | { |
| 2 | 242 | | var script = await File.ReadAllTextAsync(path, token).ConfigureAwait(false); |
| 2 | 243 | | _ = ps.AddScript(script); |
| 2 | 244 | | } |
| | 245 | |
|
| | 246 | | /// <summary> |
| | 247 | | /// Logs the execution of a PowerShell script. |
| | 248 | | /// </summary> |
| | 249 | | /// <param name="psfile">The path to the PowerShell script file.</param> |
| | 250 | | private static void LogExecution(string psfile) |
| | 251 | | { |
| 2 | 252 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 253 | | { |
| 2 | 254 | | Log.Debug("Executing PowerShell script: {ScriptFile}", psfile); |
| | 255 | | } |
| 2 | 256 | | } |
| | 257 | |
|
| | 258 | | private static Task<PSDataCollection<PSObject>> InvokePowerShellAsync(PowerShell ps) |
| 2 | 259 | | => ps.InvokeAsync(); |
| | 260 | |
|
| | 261 | | private static void LogResultsCount(int count) |
| | 262 | | { |
| 2 | 263 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 264 | | { |
| 2 | 265 | | Log.Debug("PowerShell script returned {Count} results", count); |
| | 266 | | } |
| 2 | 267 | | } |
| | 268 | |
|
| | 269 | | private static void SetModelIfPresent(PowerShell ps, HttpContext context) |
| | 270 | | { |
| 2 | 271 | | var model = ps.Runspace.SessionStateProxy.GetVariable("Model"); |
| 2 | 272 | | if (model is not null) |
| | 273 | | { |
| 1 | 274 | | context.Items[MODEL_KEY] = model; |
| | 275 | | } |
| | 276 | |
|
| 2 | 277 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 278 | | { |
| 2 | 279 | | Log.Debug("PowerShell Razor Page model set: {Model}", model); |
| | 280 | | } |
| 2 | 281 | | } |
| | 282 | |
|
| 2 | 283 | | private static bool HasErrors(PowerShell ps) => ps.HadErrors || ps.Streams.Error.Count != 0; |
| | 284 | |
|
| | 285 | | private static async Task HandleErrorsAsync(HttpContext context, PowerShell ps) |
| | 286 | | { |
| 1 | 287 | | Log.Error("PowerShell script encountered errors: {ErrorCount}", ps.Streams.Error.Count); |
| 1 | 288 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 289 | | { |
| 1 | 290 | | Log.Debug("PowerShell script errors: {Errors}", BuildError.Text(ps)); |
| | 291 | | } |
| | 292 | |
|
| 1 | 293 | | await BuildError.ResponseAsync(context, ps); |
| 1 | 294 | | } |
| | 295 | |
|
| | 296 | | private static void LogStreamsIfAny(PowerShell ps) |
| | 297 | | { |
| 1 | 298 | | if (ps.Streams.Verbose.Count > 0 || ps.Streams.Debug.Count > 0 || ps.Streams.Warning.Count > 0 || ps.Streams.Inf |
| | 299 | | { |
| 0 | 300 | | Log.Verbose("PowerShell script completed with verbose/debug/warning/info messages."); |
| 0 | 301 | | Log.Verbose(BuildError.Text(ps)); |
| | 302 | | } |
| 1 | 303 | | else if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 304 | | { |
| 1 | 305 | | Log.Debug("PowerShell script completed without errors or messages."); |
| | 306 | | } |
| 1 | 307 | | } |
| | 308 | |
|
| | 309 | | private static void ReturnRunspaceAndDispose(PowerShell? ps, KestrunRunspacePoolManager pool) |
| | 310 | | { |
| 2 | 311 | | if (ps is null) |
| | 312 | | { |
| 0 | 313 | | return; |
| | 314 | | } |
| | 315 | |
|
| 2 | 316 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 317 | | { |
| 2 | 318 | | Log.Debug("Returning runspace to pool: {RunspaceId}", ps.Runspace.InstanceId); |
| | 319 | | } |
| | 320 | |
|
| 2 | 321 | | pool.Release(ps.Runspace); |
| 2 | 322 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 323 | | { |
| 2 | 324 | | Log.Debug("Disposing PowerShell instance: {InstanceId}", ps.InstanceId); |
| | 325 | | } |
| | 326 | |
|
| 2 | 327 | | ps.Dispose(); |
| 2 | 328 | | } |
| | 329 | | } |