| | | 1 | | using System.Collections.Immutable; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Text; |
| | | 4 | | using Kestrun.SharedState; |
| | | 5 | | using Microsoft.CodeAnalysis; |
| | | 6 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 7 | | using Microsoft.CodeAnalysis.CSharp.Scripting; |
| | | 8 | | using Microsoft.CodeAnalysis.Scripting; |
| | | 9 | | using Serilog.Events; |
| | | 10 | | using Kestrun.Logging; |
| | | 11 | | using Kestrun.Hosting; |
| | | 12 | | |
| | | 13 | | namespace Kestrun.Languages; |
| | | 14 | | |
| | | 15 | | |
| | | 16 | | internal static class CSharpDelegateBuilder |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Builds a C# delegate for handling HTTP requests. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 22 | | /// <param name="code">The C# code to execute.</param> |
| | | 23 | | /// <param name="args">Arguments to inject as variables into the script.</param> |
| | | 24 | | /// <param name="extraImports">Additional namespaces to import.</param> |
| | | 25 | | /// <param name="extraRefs">Additional assemblies to reference.</param> |
| | | 26 | | /// <param name="languageVersion">The C# language version to use.</param> |
| | | 27 | | /// <returns>A delegate that handles HTTP requests.</returns> |
| | | 28 | | /// <exception cref="ArgumentNullException">Thrown if the code is null or whitespace.</exception> |
| | | 29 | | /// <exception cref="CompilationErrorException">Thrown if the C# code compilation fails.</exception> |
| | | 30 | | /// <remarks> |
| | | 31 | | /// This method compiles the provided C# code into a script and returns a delegate that can be used to handle HTTP r |
| | | 32 | | /// It supports additional imports and references, and can inject global variables into the script. |
| | | 33 | | /// The delegate will execute the provided C# code within the context of an HTTP request, allowing access to the req |
| | | 34 | | /// </remarks> |
| | | 35 | | internal static RequestDelegate Build(KestrunHost host, |
| | | 36 | | string code, Dictionary<string, object?>? args, string[]? extraImports, |
| | | 37 | | Assembly[]? extraRefs, LanguageVersion languageVersion = LanguageVersion.CSharp12) |
| | | 38 | | { |
| | 37 | 39 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 40 | | { |
| | 26 | 41 | | host.Logger.Debug("Building C# delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, l |
| | 26 | 42 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | // Validate inputs |
| | 37 | 46 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 47 | | { |
| | 1 | 48 | | throw new ArgumentNullException(nameof(code), "C# code cannot be null or whitespace."); |
| | | 49 | | } |
| | | 50 | | // 1. Compile the C# code into a script |
| | | 51 | | // - Use CSharpScript.Create() to create a script with the provided code |
| | | 52 | | // - Use ScriptOptions to specify imports, references, and language version |
| | | 53 | | // - Inject the provided arguments into the globals |
| | 36 | 54 | | var script = Compile(host: host, code: code, extraImports: extraImports, extraRefs: extraRefs, null, languageVer |
| | | 55 | | |
| | | 56 | | // 2. Return a delegate that executes the script |
| | | 57 | | // - The delegate takes an HttpContext and returns a Task |
| | | 58 | | // - It creates a KestrunContext and KestrunResponse from the HttpContext |
| | | 59 | | // - It executes the script with the provided globals and locals |
| | | 60 | | // - It applies the response to the HttpContext |
| | 36 | 61 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 62 | | { |
| | 25 | 63 | | host.Logger.Debug("C# delegate built successfully, script length={Length}, imports={ImportsCount}, refs={Ref |
| | 25 | 64 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 65 | | } |
| | | 66 | | |
| | 36 | 67 | | return async ctx => |
| | 36 | 68 | | { |
| | 36 | 69 | | try |
| | 36 | 70 | | { |
| | 15 | 71 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 72 | | { |
| | 3 | 73 | | host.Logger.DebugSanitized("Preparing execution for C# script at {Path}", ctx.Request.Path); |
| | 36 | 74 | | } |
| | 36 | 75 | | |
| | 15 | 76 | | var (Globals, Response, Context) = await DelegateBuilder.PrepareExecutionAsync(host, ctx, args).Configur |
| | 36 | 77 | | |
| | 36 | 78 | | // Execute the script with the current context and shared state |
| | 15 | 79 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 80 | | { |
| | 3 | 81 | | host.Logger.DebugSanitized("Executing C# script for {Path}", ctx.Request.Path); |
| | 36 | 82 | | } |
| | 36 | 83 | | |
| | 15 | 84 | | _ = await script.RunAsync(Globals).ConfigureAwait(false); |
| | 10 | 85 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 86 | | { |
| | 3 | 87 | | host.Logger.DebugSanitized("C# script executed successfully for {Path}", ctx.Request.Path); |
| | 36 | 88 | | } |
| | 36 | 89 | | |
| | 36 | 90 | | // Apply the response to the Kestrun context |
| | 10 | 91 | | await DelegateBuilder.ApplyResponseAsync(ctx, Response, host.Logger).ConfigureAwait(false); |
| | 10 | 92 | | } |
| | 36 | 93 | | finally |
| | 36 | 94 | | { |
| | 36 | 95 | | // Intentionally do not call Response.CompleteAsync here to keep the pipeline open |
| | 36 | 96 | | // for middleware like StatusCodePages to generate bodies for status-only responses. |
| | 36 | 97 | | } |
| | 46 | 98 | | }; |
| | | 99 | | } |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Compiles the provided C# code into a script. |
| | | 103 | | /// This method supports additional imports and references, and can inject global variables into the script. |
| | | 104 | | /// It returns a compiled script that can be executed later. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 107 | | /// <param name="code">The C# code to compile.</param> |
| | | 108 | | /// <param name="extraImports">Additional namespaces to import.</param> |
| | | 109 | | /// <param name="extraRefs">Additional assembly references.</param> |
| | | 110 | | /// <param name="locals">Local variables to inject into the script.</param> |
| | | 111 | | /// <param name="languageVersion">The C# language version to use.</param> |
| | | 112 | | /// <returns>A compiled script that can be executed later.</returns> |
| | | 113 | | /// <exception cref="ArgumentNullException">Thrown when the code is null or whitespace.</exception> |
| | | 114 | | /// <exception cref="CompilationErrorException">Thrown when there are compilation errors.</exception> |
| | | 115 | | /// <remarks> |
| | | 116 | | /// This method compiles the provided C# code into a script using Roslyn. |
| | | 117 | | /// It supports additional imports and references, and can inject global variables into the script. |
| | | 118 | | /// The script can be executed later with the provided globals and locals. |
| | | 119 | | /// It is useful for scenarios where dynamic C# code execution is required, such as in web applications or scripting |
| | | 120 | | /// </remarks> |
| | | 121 | | internal static Script<object> Compile( |
| | | 122 | | KestrunHost host, |
| | | 123 | | string? code, string[]? extraImports, |
| | | 124 | | Assembly[]? extraRefs, IReadOnlyDictionary<string, object?>? locals, LanguageVersion languageVersion = Langu |
| | | 125 | | ) |
| | | 126 | | { |
| | 59 | 127 | | var log = host.Logger; |
| | 59 | 128 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 129 | | { |
| | 48 | 130 | | log.Debug("Compiling C# script, length={Length}, imports={ImportsCount}, refs={RefsCount}, lang={Lang}", |
| | 48 | 131 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 132 | | } |
| | | 133 | | |
| | | 134 | | // Validate inputs |
| | 59 | 135 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 136 | | { |
| | 0 | 137 | | throw new ArgumentNullException(nameof(code), "C# code cannot be null or whitespace."); |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | // References and imports |
| | 59 | 141 | | var coreRefs = DelegateBuilder.BuildBaselineReferences(); |
| | | 142 | | // Core references + Kestrun + extras |
| | | 143 | | // Note: Order matters, Kestrun must come after core to avoid conflicts |
| | 59 | 144 | | var kestrunAssembly = typeof(KestrunHost).Assembly; // Kestrun.dll |
| | 59 | 145 | | var kestrunRef = MetadataReference.CreateFromFile(kestrunAssembly.Location); |
| | 59 | 146 | | var kestrunNamespaces = CollectKestrunNamespaces(kestrunAssembly); |
| | | 147 | | // Create script options |
| | 59 | 148 | | var opts = CreateScriptOptions(DelegateBuilder.PlatformImports, kestrunNamespaces, coreRefs, kestrunRef); |
| | 59 | 149 | | opts = AddExtraImports(opts, extraImports); |
| | 59 | 150 | | opts = AddExtraReferences(opts, extraRefs, log); |
| | | 151 | | |
| | | 152 | | // Include currently loaded assemblies (deduplicated) to minimize missing reference issues. |
| | 59 | 153 | | opts = AddLoadedAssemblyReferences(opts, log); |
| | | 154 | | |
| | | 155 | | // Globals/locals injection plus dynamic discovery of namespaces & assemblies needed |
| | 59 | 156 | | var (CodeWithPreamble, DynamicImports, DynamicReferences) = BuildGlobalsAndLocalsPreamble(host, code, locals); |
| | 59 | 157 | | code = CodeWithPreamble; |
| | | 158 | | |
| | 59 | 159 | | if (DynamicImports.Count > 0) |
| | | 160 | | { |
| | 22 | 161 | | var newImports = DynamicImports.Except(opts.Imports, StringComparer.Ordinal).ToArray(); |
| | 22 | 162 | | if (newImports.Length > 0) |
| | | 163 | | { |
| | 0 | 164 | | opts = opts.WithImports(opts.Imports.Concat(newImports)); |
| | 0 | 165 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 166 | | { |
| | 0 | 167 | | log.Debug("Added {ImportCount} dynamic imports derived from globals/locals: {Imports}", newImports.L |
| | | 168 | | } |
| | | 169 | | } |
| | | 170 | | } |
| | | 171 | | |
| | 59 | 172 | | if (DynamicReferences.Count > 0) |
| | | 173 | | { |
| | | 174 | | // Avoid duplicates by location |
| | 22 | 175 | | var existingRefPaths = new HashSet<string>(opts.MetadataReferences |
| | 22 | 176 | | .OfType<PortableExecutableReference>() |
| | 5460 | 177 | | .Select(r => r.FilePath ?? string.Empty) |
| | 5482 | 178 | | .Where(p => !string.IsNullOrEmpty(p)), StringComparer.OrdinalIgnoreCase); |
| | | 179 | | |
| | 22 | 180 | | var newRefs = DynamicReferences |
| | 22 | 181 | | .Where(r => !string.IsNullOrEmpty(r.Location) && File.Exists(r.Location) && !existingRefPaths.Contains(r |
| | 0 | 182 | | .Select(r => MetadataReference.CreateFromFile(r.Location)) |
| | 22 | 183 | | .ToArray(); |
| | | 184 | | |
| | 22 | 185 | | if (newRefs.Length > 0) |
| | | 186 | | { |
| | 0 | 187 | | opts = opts.WithReferences(opts.MetadataReferences.Concat(newRefs)); |
| | 0 | 188 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 189 | | { |
| | 0 | 190 | | log.Debug("Added {RefCount} dynamic assembly reference(s) derived from globals/locals.", newRefs.Len |
| | | 191 | | } |
| | | 192 | | } |
| | | 193 | | } |
| | | 194 | | |
| | | 195 | | // Compile |
| | 59 | 196 | | var script = CSharpScript.Create(code, opts, typeof(CsGlobals)); |
| | 59 | 197 | | var diagnostics = CompileAndGetDiagnostics(script, log); |
| | 59 | 198 | | ThrowIfDiagnosticsNull(diagnostics); |
| | 59 | 199 | | ThrowOnErrors(diagnostics, log); |
| | 58 | 200 | | LogWarnings(diagnostics, log); |
| | 58 | 201 | | LogSuccessIfNoWarnings(diagnostics, log); |
| | | 202 | | |
| | 58 | 203 | | return script; |
| | | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <summary>Collects metadata references for all non-dynamic loaded assemblies with a physical location.</summary> |
| | | 207 | | /// <param name="log">Logger.</param> |
| | | 208 | | /// <returns>Tuple of references and total count considered.</returns> |
| | | 209 | | private static (IEnumerable<MetadataReference> Refs, int Total) CollectLoadedAssemblyReferences(Serilog.ILogger log) |
| | | 210 | | { |
| | | 211 | | try |
| | | 212 | | { |
| | 59 | 213 | | var loaded = AppDomain.CurrentDomain.GetAssemblies(); |
| | 59 | 214 | | var refs = new List<MetadataReference>(loaded.Length); |
| | 59 | 215 | | var considered = 0; |
| | 35220 | 216 | | foreach (var a in loaded) |
| | | 217 | | { |
| | 17551 | 218 | | considered++; |
| | 17551 | 219 | | if (a.IsDynamic) |
| | | 220 | | { |
| | | 221 | | continue; |
| | | 222 | | } |
| | 17329 | 223 | | if (string.IsNullOrEmpty(a.Location) || !File.Exists(a.Location)) |
| | | 224 | | { |
| | | 225 | | continue; |
| | | 226 | | } |
| | | 227 | | try |
| | | 228 | | { |
| | 14765 | 229 | | refs.Add(MetadataReference.CreateFromFile(a.Location)); |
| | 14765 | 230 | | } |
| | 0 | 231 | | catch (Exception ex) |
| | | 232 | | { |
| | 0 | 233 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 234 | | { |
| | 0 | 235 | | log.Debug(ex, "Failed to add loaded assembly reference: {Assembly}", a.FullName); |
| | | 236 | | } |
| | 0 | 237 | | } |
| | | 238 | | } |
| | 59 | 239 | | return (refs, considered); |
| | | 240 | | } |
| | 0 | 241 | | catch (Exception ex) |
| | | 242 | | { |
| | 0 | 243 | | log.Warning(ex, "Failed to enumerate loaded assemblies for dynamic references."); |
| | 0 | 244 | | return (Array.Empty<MetadataReference>(), 0); |
| | | 245 | | } |
| | 59 | 246 | | } |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// Builds the core assembly references for the script. |
| | | 250 | | /// </summary> |
| | | 251 | | /// <returns>The core assembly references.</returns> |
| | | 252 | | |
| | | 253 | | /// <summary> |
| | | 254 | | /// Collects the namespaces from the Kestrun assembly. |
| | | 255 | | /// </summary> |
| | | 256 | | /// <param name="kestrunAssembly">The Kestrun assembly.</param> |
| | | 257 | | /// <returns>The collected namespaces.</returns> |
| | | 258 | | private static string[] CollectKestrunNamespaces(Assembly kestrunAssembly) |
| | | 259 | | { |
| | 59 | 260 | | return [.. kestrunAssembly |
| | 59 | 261 | | .GetExportedTypes() |
| | 10974 | 262 | | .Select(t => t.Namespace) |
| | 10974 | 263 | | .Where(ns => !string.IsNullOrEmpty(ns) && ns!.StartsWith("Kestrun", StringComparison.Ordinal)) |
| | 10974 | 264 | | .Select(ns => ns!) |
| | 59 | 265 | | .Distinct()]; |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | /// <summary> |
| | | 269 | | /// Creates script options for the VB.NET script. |
| | | 270 | | /// </summary> |
| | | 271 | | /// <param name="platformImports">The platform-specific namespaces to import.</param> |
| | | 272 | | /// <param name="kestrunNamespaces">The Kestrun-specific namespaces to import.</param> |
| | | 273 | | /// <param name="coreRefs">The core assembly references to include.</param> |
| | | 274 | | /// <param name="kestrunRef">The Kestrun assembly reference to include.</param> |
| | | 275 | | /// <returns>The created script options.</returns> |
| | | 276 | | private static ScriptOptions CreateScriptOptions( |
| | | 277 | | IEnumerable<string> platformImports, |
| | | 278 | | IEnumerable<string> kestrunNamespaces, |
| | | 279 | | IEnumerable<MetadataReference> coreRefs, |
| | | 280 | | MetadataReference kestrunRef) |
| | | 281 | | { |
| | 59 | 282 | | var allImports = platformImports.Concat(kestrunNamespaces) ?? []; |
| | | 283 | | // Keep default references then add our core + Kestrun to avoid losing essential BCL assemblies |
| | 59 | 284 | | var opts = ScriptOptions.Default |
| | 59 | 285 | | .WithImports(allImports) |
| | 59 | 286 | | .AddReferences(coreRefs) |
| | 59 | 287 | | .AddReferences(kestrunRef); |
| | 59 | 288 | | return opts; |
| | | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <summary> |
| | | 292 | | /// Adds extra using directives to the script options. |
| | | 293 | | /// </summary> |
| | | 294 | | /// <param name="opts">The script options to modify.</param> |
| | | 295 | | /// <param name="extraImports">The extra using directives to add.</param> |
| | | 296 | | /// <returns>The modified script options.</returns> |
| | | 297 | | private static ScriptOptions AddExtraImports(ScriptOptions opts, string[]? extraImports) |
| | | 298 | | { |
| | 59 | 299 | | extraImports ??= ["Kestrun"]; |
| | 59 | 300 | | if (!extraImports.Contains("Kestrun")) |
| | | 301 | | { |
| | 1 | 302 | | var importsList = extraImports.ToList(); |
| | 1 | 303 | | importsList.Add("Kestrun"); |
| | 1 | 304 | | extraImports = [.. importsList]; |
| | | 305 | | } |
| | 59 | 306 | | return extraImports.Length > 0 |
| | 59 | 307 | | ? opts.WithImports(opts.Imports.Concat(extraImports)) |
| | 59 | 308 | | : opts; |
| | | 309 | | } |
| | | 310 | | |
| | | 311 | | /// <summary> |
| | | 312 | | /// Adds extra assembly references to the script options. |
| | | 313 | | /// </summary> |
| | | 314 | | /// <param name="opts">The script options to modify.</param> |
| | | 315 | | /// <param name="extraRefs">The extra assembly references to add.</param> |
| | | 316 | | /// <param name="log">The logger to use for logging.</param> |
| | | 317 | | /// <returns>The modified script options.</returns> |
| | | 318 | | private static ScriptOptions AddExtraReferences(ScriptOptions opts, Assembly[]? extraRefs, Serilog.ILogger log) |
| | | 319 | | { |
| | 59 | 320 | | if (extraRefs is not { Length: > 0 }) |
| | | 321 | | { |
| | 59 | 322 | | return opts; |
| | | 323 | | } |
| | | 324 | | |
| | 0 | 325 | | foreach (var r in extraRefs) |
| | | 326 | | { |
| | 0 | 327 | | if (string.IsNullOrEmpty(r.Location)) |
| | | 328 | | { |
| | 0 | 329 | | log.Warning("Skipping dynamic assembly with no location: {Assembly}", r.FullName); |
| | | 330 | | } |
| | 0 | 331 | | else if (!File.Exists(r.Location)) |
| | | 332 | | { |
| | 0 | 333 | | log.Warning("Skipping missing assembly file: {Location}", r.Location); |
| | | 334 | | } |
| | | 335 | | } |
| | | 336 | | |
| | 0 | 337 | | var safeRefs = extraRefs |
| | 0 | 338 | | .Where(r => !string.IsNullOrEmpty(r.Location) && File.Exists(r.Location)) |
| | 0 | 339 | | .Select(r => MetadataReference.CreateFromFile(r.Location)); |
| | | 340 | | |
| | 0 | 341 | | return opts.WithReferences(opts.MetadataReferences.Concat(safeRefs)); |
| | | 342 | | } |
| | | 343 | | |
| | | 344 | | /// <summary> |
| | | 345 | | /// Adds references for all currently loaded (non-duplicate) assemblies to the script options. |
| | | 346 | | /// </summary> |
| | | 347 | | /// <param name="opts">Current script options.</param> |
| | | 348 | | /// <param name="log">Logger.</param> |
| | | 349 | | /// <returns>Updated script options.</returns> |
| | | 350 | | private static ScriptOptions AddLoadedAssemblyReferences(ScriptOptions opts, Serilog.ILogger log) |
| | | 351 | | { |
| | | 352 | | // Optionally include all currently loaded assemblies to reduce missing reference issues. |
| | | 353 | | // Roslyn will de-duplicate by file path internally but we still filter to avoid redundant work. |
| | 59 | 354 | | var (loadedRefs, loadedCount) = CollectLoadedAssemblyReferences(log); |
| | 59 | 355 | | if (loadedCount <= 0) |
| | | 356 | | { |
| | 0 | 357 | | return opts; |
| | | 358 | | } |
| | | 359 | | |
| | 59 | 360 | | var existingPaths = new HashSet<string>(opts.MetadataReferences |
| | 59 | 361 | | .OfType<PortableExecutableReference>() |
| | 10637 | 362 | | .Select(r => r.FilePath ?? string.Empty) |
| | 10696 | 363 | | .Where(p => !string.IsNullOrEmpty(p)), StringComparer.OrdinalIgnoreCase); |
| | | 364 | | |
| | 59 | 365 | | var newLoadedRefs = loadedRefs |
| | 14765 | 366 | | .Where(r => r is PortableExecutableReference pe && !string.IsNullOrEmpty(pe.FilePath) && !existingPaths.Cont |
| | 59 | 367 | | .ToArray(); |
| | | 368 | | |
| | 59 | 369 | | if (newLoadedRefs.Length == 0) |
| | | 370 | | { |
| | 0 | 371 | | return opts; |
| | | 372 | | } |
| | | 373 | | |
| | 59 | 374 | | var updated = opts.WithReferences(opts.MetadataReferences.Concat(newLoadedRefs)); |
| | 59 | 375 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 376 | | { |
| | 48 | 377 | | log.Debug("Added {RefCount} loaded assembly reference(s) (of {TotalLoaded}) for dynamic script compilation." |
| | | 378 | | } |
| | 59 | 379 | | return updated; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | /// <summary> |
| | | 383 | | /// Prepends global and local variable declarations to the provided code. |
| | | 384 | | /// </summary> |
| | | 385 | | ///<param name="host">The Kestrun host instance.</param> |
| | | 386 | | /// <param name="code">The original code to modify.</param> |
| | | 387 | | /// <param name="locals">The local variables to include.</param> |
| | | 388 | | /// <returns>The modified code with global and local variable declarations.</returns> |
| | | 389 | | /// <summary>Builds the preamble variable declarations for globals & locals and discovers required namespaces an |
| | | 390 | | /// <returns>Tuple containing code with preamble, dynamic imports, dynamic references.</returns> |
| | | 391 | | private static (string CodeWithPreamble, List<string> DynamicImports, List<Assembly> DynamicReferences) BuildGlobals |
| | | 392 | | KestrunHost host, |
| | | 393 | | string? code, |
| | | 394 | | IReadOnlyDictionary<string, object?>? locals) |
| | | 395 | | { |
| | | 396 | | // Merge globals + locals |
| | 59 | 397 | | var merged = MergeGlobalsAndLocals(host, locals); |
| | | 398 | | |
| | | 399 | | // Build preamble & discover dynamic imports/refs |
| | 59 | 400 | | var (preamble, imports, refs) = GeneratePreambleAndDiscover(merged); |
| | | 401 | | |
| | | 402 | | // Append original code |
| | 59 | 403 | | var finalCode = preamble.Length > 0 ? preamble + (code ?? string.Empty) : code ?? string.Empty; |
| | | 404 | | |
| | | 405 | | // Filter references to only those with locations |
| | 81 | 406 | | var filteredRefs = refs.Where(r => !string.IsNullOrEmpty(r.Location)).ToList(); |
| | | 407 | | |
| | 59 | 408 | | LogDynamicDiscovery(imports, filteredRefs, host.Logger); |
| | | 409 | | |
| | 59 | 410 | | return (finalCode, imports.ToList(), filteredRefs); |
| | | 411 | | } |
| | | 412 | | |
| | | 413 | | /// <summary> |
| | | 414 | | /// Creates a merged dictionary of global shared state and the supplied <paramref name="locals"/>. |
| | | 415 | | /// Local values override globals when a key collision occurs (case-insensitive). |
| | | 416 | | /// </summary> |
| | | 417 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 418 | | /// <param name="locals">Optional locals dictionary passed in at compile time.</param> |
| | | 419 | | /// <returns>A mutable dictionary keyed by variable name mapping to its source store name and value.</returns> |
| | | 420 | | private static Dictionary<string, (string Dict, object? Value)> MergeGlobalsAndLocals( |
| | | 421 | | KestrunHost host, |
| | | 422 | | IReadOnlyDictionary<string, object?>? locals) |
| | | 423 | | { |
| | 59 | 424 | | var merged = new Dictionary<string, (string Dict, object? Value)>(StringComparer.OrdinalIgnoreCase); |
| | 118 | 425 | | foreach (var g in GlobalStore.Snapshot()) |
| | | 426 | | { |
| | 0 | 427 | | merged[g.Key] = ("Globals", g.Value); |
| | | 428 | | } |
| | | 429 | | // Also include host-level shared state |
| | | 430 | | // if host shared state has same key as global, host takes precedence |
| | 126 | 431 | | foreach (var g in host.SharedState.Snapshot()) |
| | | 432 | | { |
| | 4 | 433 | | merged[g.Key] = ("Globals", g.Value); |
| | | 434 | | } |
| | | 435 | | // Now overlay locals |
| | | 436 | | // if local has same key as global, local takes precedence |
| | 59 | 437 | | if (locals is { Count: > 0 }) |
| | | 438 | | { |
| | 80 | 439 | | foreach (var l in locals) |
| | | 440 | | { |
| | 21 | 441 | | merged[l.Key] = ("Locals", l.Value); |
| | | 442 | | } |
| | | 443 | | } |
| | 59 | 444 | | return merged; |
| | | 445 | | } |
| | | 446 | | |
| | | 447 | | /// <summary> |
| | | 448 | | /// Iterates all merged global + local variables and builds a textual preamble of variable declarations. |
| | | 449 | | /// While building, collects the required namespace imports and assembly references inferred from the runtime value |
| | | 450 | | /// </summary> |
| | | 451 | | /// <param name="merged">Merged globals + locals produced by <see cref="MergeGlobalsAndLocals"/>.</param> |
| | | 452 | | /// <returns>Tuple containing the preamble text builder, discovered namespace import set, and assembly reference set |
| | | 453 | | private static (StringBuilder Preamble, HashSet<string> Imports, HashSet<Assembly> Refs) GeneratePreambleAndDiscover |
| | | 454 | | Dictionary<string, (string Dict, object? Value)> merged) |
| | | 455 | | { |
| | 59 | 456 | | var preambleBuilder = new StringBuilder(); |
| | 59 | 457 | | var dynamicImports = new HashSet<string>(StringComparer.Ordinal); |
| | 59 | 458 | | var dynamicRefs = new HashSet<Assembly>(); |
| | | 459 | | |
| | 166 | 460 | | foreach (var kvp in merged) |
| | | 461 | | { |
| | 24 | 462 | | AppendVariableDeclarationAndCollect(kvp, preambleBuilder, dynamicImports, dynamicRefs); |
| | | 463 | | } |
| | | 464 | | |
| | 59 | 465 | | return (preambleBuilder, dynamicImports, dynamicRefs); |
| | | 466 | | } |
| | | 467 | | |
| | | 468 | | /// <summary> |
| | | 469 | | /// Appends a single variable declaration for the provided key/value and gathers any dynamic imports & reference |
| | | 470 | | /// </summary> |
| | | 471 | | /// <param name="kvp">The merged key and its (source dictionary name, value).</param> |
| | | 472 | | /// <param name="preambleBuilder">Builder accumulating declaration lines.</param> |
| | | 473 | | /// <param name="dynamicImports">Set capturing namespaces to import.</param> |
| | | 474 | | /// <param name="dynamicRefs">Set capturing assemblies that must be referenced.</param> |
| | | 475 | | private static void AppendVariableDeclarationAndCollect( |
| | | 476 | | KeyValuePair<string, (string Dict, object? Value)> kvp, |
| | | 477 | | StringBuilder preambleBuilder, |
| | | 478 | | HashSet<string> dynamicImports, |
| | | 479 | | HashSet<Assembly> dynamicRefs) |
| | | 480 | | { |
| | 24 | 481 | | var valueType = kvp.Value.Value?.GetType(); |
| | 24 | 482 | | var typeName = FormatTypeName(valueType); |
| | 24 | 483 | | _ = preambleBuilder.AppendLine($"var {kvp.Key} = ({typeName}){kvp.Value.Dict}[\"{kvp.Key}\"]; "); |
| | | 484 | | |
| | 24 | 485 | | if (valueType == null) |
| | | 486 | | { |
| | 0 | 487 | | return; |
| | | 488 | | } |
| | | 489 | | |
| | 24 | 490 | | TryAddNamespace(dynamicImports, valueType.Namespace); |
| | 24 | 491 | | CollectGenericArguments(valueType, dynamicImports, dynamicRefs); |
| | 24 | 492 | | _ = dynamicRefs.Add(valueType.Assembly); |
| | 24 | 493 | | } |
| | | 494 | | |
| | | 495 | | /// <summary> |
| | | 496 | | /// Adds a namespace string to the imports set if it is non-empty. |
| | | 497 | | /// </summary> |
| | | 498 | | /// <param name="imports">Namespace accumulator set.</param> |
| | | 499 | | /// <param name="ns">Namespace candidate.</param> |
| | | 500 | | private static void TryAddNamespace(HashSet<string> imports, string? ns) |
| | | 501 | | { |
| | 27 | 502 | | if (!string.IsNullOrEmpty(ns)) |
| | | 503 | | { |
| | 27 | 504 | | _ = imports.Add(ns); |
| | | 505 | | } |
| | 27 | 506 | | } |
| | | 507 | | |
| | | 508 | | /// <summary> |
| | | 509 | | /// For a generic type, collects namespaces and assemblies for each generic argument. |
| | | 510 | | /// </summary> |
| | | 511 | | /// <param name="valueType">The possibly generic value type.</param> |
| | | 512 | | /// <param name="imports">Namespace accumulator set.</param> |
| | | 513 | | /// <param name="refs">Assembly reference accumulator set.</param> |
| | | 514 | | private static void CollectGenericArguments(Type valueType, HashSet<string> imports, HashSet<Assembly> refs) |
| | | 515 | | { |
| | 24 | 516 | | if (!valueType.IsGenericType) |
| | | 517 | | { |
| | 22 | 518 | | return; |
| | | 519 | | } |
| | 10 | 520 | | foreach (var ga in valueType.GetGenericArguments()) |
| | | 521 | | { |
| | 3 | 522 | | TryAddNamespace(imports, ga.Namespace); |
| | 3 | 523 | | _ = refs.Add(ga.Assembly); |
| | | 524 | | } |
| | 2 | 525 | | } |
| | | 526 | | |
| | | 527 | | /// <summary> |
| | | 528 | | /// Emits a debug log summarizing the dynamic imports and assembly references that were discovered. |
| | | 529 | | /// </summary> |
| | | 530 | | /// <param name="imports">Collected imports.</param> |
| | | 531 | | /// <param name="refs">Collected assembly references (filtered to those with physical locations).</param> |
| | | 532 | | /// <param name="log">Logger.</param> |
| | | 533 | | private static void LogDynamicDiscovery(HashSet<string> imports, List<Assembly> refs, Serilog.ILogger log) |
| | | 534 | | { |
| | 59 | 535 | | if (log.IsEnabled(LogEventLevel.Debug) && (imports.Count > 0 || refs.Count > 0)) |
| | | 536 | | { |
| | 22 | 537 | | log.Debug("Discovered {ImportCount} dynamic import(s) and {RefCount} reference(s) from globals/locals.", imp |
| | | 538 | | } |
| | 59 | 539 | | } |
| | | 540 | | |
| | | 541 | | // Produces a C# friendly type name for reflection types (handles generics, arrays, nullable, and fallbacks). |
| | | 542 | | private static string FormatTypeName(Type? t) |
| | | 543 | | { |
| | 28 | 544 | | if (t == null) |
| | | 545 | | { |
| | 0 | 546 | | return "object"; |
| | | 547 | | } |
| | 28 | 548 | | if (t.IsGenericParameter) |
| | | 549 | | { |
| | 0 | 550 | | return "object"; |
| | | 551 | | } |
| | 28 | 552 | | if (t.IsArray) |
| | | 553 | | { |
| | 1 | 554 | | return FormatTypeName(t.GetElementType()) + "[]"; |
| | | 555 | | } |
| | | 556 | | // Nullable<T> |
| | 27 | 557 | | if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) |
| | | 558 | | { |
| | 0 | 559 | | return FormatTypeName(t.GetGenericArguments()[0]) + "?"; |
| | | 560 | | } |
| | 27 | 561 | | if (t.IsGenericType) |
| | | 562 | | { |
| | | 563 | | try |
| | | 564 | | { |
| | 2 | 565 | | var genericDefName = t.Name; |
| | 2 | 566 | | var tickIndex = genericDefName.IndexOf('`'); |
| | 2 | 567 | | if (tickIndex > 0) |
| | | 568 | | { |
| | 2 | 569 | | genericDefName = genericDefName[..tickIndex]; |
| | | 570 | | } |
| | 2 | 571 | | var args = t.GetGenericArguments().Select(FormatTypeName); |
| | 2 | 572 | | return (t.Namespace != null ? t.Namespace + "." : string.Empty) + genericDefName + "<" + string.Join("," |
| | | 573 | | } |
| | 0 | 574 | | catch |
| | | 575 | | { |
| | 0 | 576 | | return "object"; |
| | | 577 | | } |
| | | 578 | | } |
| | | 579 | | // Non generic |
| | 25 | 580 | | return t.FullName ?? t.Name ?? "object"; |
| | 2 | 581 | | } |
| | | 582 | | |
| | | 583 | | /// <summary> |
| | | 584 | | /// Compiles the provided VB.NET script and returns any diagnostics. |
| | | 585 | | /// </summary> |
| | | 586 | | /// <param name="script">The VB.NET script to compile.</param> |
| | | 587 | | /// <param name="log">The logger to use for logging.</param> |
| | | 588 | | /// <returns>A collection of diagnostics produced during compilation, or null if compilation failed.</returns> |
| | | 589 | | private static ImmutableArray<Diagnostic>? CompileAndGetDiagnostics(Script<object> script, Serilog.ILogger log) |
| | | 590 | | { |
| | | 591 | | try |
| | | 592 | | { |
| | 59 | 593 | | return script.Compile(); |
| | | 594 | | } |
| | 0 | 595 | | catch (CompilationErrorException ex) |
| | | 596 | | { |
| | 0 | 597 | | log.Error(ex, "C# script compilation failed with errors."); |
| | 0 | 598 | | return null; |
| | | 599 | | } |
| | 59 | 600 | | } |
| | | 601 | | |
| | | 602 | | private static void ThrowIfDiagnosticsNull(ImmutableArray<Diagnostic>? diagnostics) |
| | | 603 | | { |
| | 59 | 604 | | if (diagnostics == null) |
| | | 605 | | { |
| | 0 | 606 | | throw new CompilationErrorException("C# script compilation failed with no diagnostics.", []); |
| | | 607 | | } |
| | 59 | 608 | | } |
| | | 609 | | |
| | | 610 | | /// <summary> |
| | | 611 | | /// Throws a CompilationErrorException if the diagnostics are null. |
| | | 612 | | /// </summary> |
| | | 613 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 614 | | /// <param name="log">The logger to use for logging.</param> |
| | | 615 | | /// <exception cref="CompilationErrorException"></exception> |
| | | 616 | | private static void ThrowOnErrors(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 617 | | { |
| | 60 | 618 | | if (diagnostics?.Any(d => d.Severity == DiagnosticSeverity.Error) != true) |
| | | 619 | | { |
| | 58 | 620 | | return; |
| | | 621 | | } |
| | | 622 | | |
| | 2 | 623 | | var errors = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); |
| | 1 | 624 | | if (errors is not { Length: > 0 }) |
| | | 625 | | { |
| | 0 | 626 | | return; |
| | | 627 | | } |
| | | 628 | | |
| | 1 | 629 | | var sb = new StringBuilder(); |
| | 1 | 630 | | _ = sb.AppendLine($"C# script compilation completed with {errors.Length} error(s):"); |
| | 4 | 631 | | foreach (var error in errors) |
| | | 632 | | { |
| | 1 | 633 | | var location = error.Location.IsInSource |
| | 1 | 634 | | ? $" at line {error.Location.GetLineSpan().StartLinePosition.Line + 1}" |
| | 1 | 635 | | : string.Empty; |
| | 1 | 636 | | var msg = $" Error [{error.Id}]: {error.GetMessage()}{location}"; |
| | 1 | 637 | | log.Error(msg); |
| | 1 | 638 | | _ = sb.AppendLine(msg); |
| | | 639 | | } |
| | 1 | 640 | | throw new CompilationErrorException("C# route code compilation failed\n" + sb.ToString(), diagnostics ?? []); |
| | | 641 | | } |
| | | 642 | | |
| | | 643 | | /// <summary> |
| | | 644 | | /// Logs warning messages if the compilation succeeded with warnings. |
| | | 645 | | /// </summary> |
| | | 646 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 647 | | /// <param name="log">The logger to use for logging.</param> |
| | | 648 | | private static void LogWarnings(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 649 | | { |
| | 58 | 650 | | var warnings = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | 58 | 651 | | if (warnings is not null && warnings.Length != 0) |
| | | 652 | | { |
| | 0 | 653 | | log.Warning($"C# script compilation completed with {warnings.Length} warning(s):"); |
| | 0 | 654 | | foreach (var warning in warnings) |
| | | 655 | | { |
| | 0 | 656 | | var location = warning.Location.IsInSource |
| | 0 | 657 | | ? $" at line {warning.Location.GetLineSpan().StartLinePosition.Line + 1}" |
| | 0 | 658 | | : string.Empty; |
| | 0 | 659 | | log.Warning($" Warning [{warning.Id}]: {warning.GetMessage()}{location}"); |
| | | 660 | | } |
| | | 661 | | } |
| | 58 | 662 | | } |
| | | 663 | | |
| | | 664 | | /// <summary> |
| | | 665 | | /// Logs a success message if the compilation succeeded without warnings. |
| | | 666 | | /// </summary> |
| | | 667 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 668 | | /// <param name="log">The logger to use for logging.</param> |
| | | 669 | | private static void LogSuccessIfNoWarnings(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 670 | | { |
| | 58 | 671 | | var warnings = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | 58 | 672 | | if (warnings != null && warnings.Length == 0 && log.IsEnabled(LogEventLevel.Debug)) |
| | | 673 | | { |
| | 47 | 674 | | log.Debug("C# script compiled successfully with no warnings."); |
| | | 675 | | } |
| | 58 | 676 | | } |
| | | 677 | | } |