| | | 1 | | using System.Management.Automation; |
| | | 2 | | using Kestrun.Scripting; |
| | | 3 | | using Kestrun.SharedState; |
| | | 4 | | using Kestrun.Utilities; |
| | | 5 | | using Kestrun.Languages; |
| | | 6 | | using Kestrun.Hosting.Options; |
| | | 7 | | |
| | | 8 | | namespace Kestrun.Tasks; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Factory to create task job delegates for different scripting languages. |
| | | 12 | | /// </summary> |
| | | 13 | | internal static class TaskJobFactory |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Configuration for creating a task job delegate. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="TaskId">Unique identifier of the task.</param> |
| | | 19 | | /// <param name="ScriptCode">The language options containing the script code and settings.</param> |
| | | 20 | | /// <param name="Log">Logger instance for logging.</param> |
| | | 21 | | /// <param name="Pool">Optional PowerShell runspace pool.</param> |
| | | 22 | | /// <param name="Progress">Progress state object to expose to scripts.</param> |
| | 15 | 23 | | internal record TaskJobConfig( |
| | 4 | 24 | | string TaskId, |
| | 78 | 25 | | LanguageOptions ScriptCode, |
| | 15 | 26 | | Serilog.ILogger Log, |
| | 16 | 27 | | KestrunRunspacePoolManager? Pool, |
| | 15 | 28 | | ProgressiveKestrunTaskState Progress |
| | 15 | 29 | | ); |
| | | 30 | | |
| | | 31 | | internal static Func<CancellationToken, Task<object?>> Create(TaskJobConfig config) |
| | 15 | 32 | | => config.ScriptCode.Language switch |
| | 15 | 33 | | { |
| | 15 | 34 | | ScriptLanguage.PowerShell => |
| | 4 | 35 | | config.Pool is null |
| | 4 | 36 | | ? throw new InvalidOperationException("PowerShell runspace pool must be provided for PowerShell task |
| | 4 | 37 | | : PowerShellTask(config), |
| | 10 | 38 | | ScriptLanguage.CSharp => CSharpTask(config), |
| | 1 | 39 | | ScriptLanguage.VBNet => VbNetTask(config), |
| | 0 | 40 | | _ => throw new NotSupportedException($"Language {config.ScriptCode.Language} not supported."), |
| | 15 | 41 | | }; |
| | | 42 | | |
| | | 43 | | private static Func<CancellationToken, Task<object?>> PowerShellTask(TaskJobConfig config) |
| | | 44 | | { |
| | 4 | 45 | | return async ct => |
| | 4 | 46 | | { |
| | 4 | 47 | | if (config.Pool is null) |
| | 4 | 48 | | { |
| | 0 | 49 | | throw new InvalidOperationException("PowerShell runspace pool must be provided for PowerShell tasks."); |
| | 4 | 50 | | } |
| | 4 | 51 | | var runspace = config.Pool.Acquire(); |
| | 4 | 52 | | try |
| | 4 | 53 | | { |
| | 4 | 54 | | using var ps = PowerShell.Create(); |
| | 4 | 55 | | ps.Runspace = runspace; |
| | 4 | 56 | | _ = ps.AddScript(config.ScriptCode.Code); |
| | 4 | 57 | | |
| | 4 | 58 | | // Merge arguments and inject Progress variable for cooperative updates |
| | 4 | 59 | | var vars = config.ScriptCode.Arguments is { Count: > 0 } |
| | 4 | 60 | | ? new Dictionary<string, object?>(config.ScriptCode.Arguments) |
| | 4 | 61 | | : []; |
| | 4 | 62 | | vars["TaskProgress"] = config.Progress; |
| | 4 | 63 | | vars["TaskId"] = config.TaskId; |
| | 4 | 64 | | PowerShellExecutionHelpers.SetVariables(ps, vars, config.Log); |
| | 6 | 65 | | using var reg = ct.Register(() => ps.Stop()); |
| | 4 | 66 | | var results = await ps.InvokeAsync().WaitAsync(ct).ConfigureAwait(false); |
| | 4 | 67 | | |
| | 4 | 68 | | // Collect pipeline output (base objects) as an object[] |
| | 1 | 69 | | var output = results.Count == 0 |
| | 1 | 70 | | ? null |
| | 2 | 71 | | : results.Select(r => r.BaseObject).ToArray(); |
| | 4 | 72 | | |
| | 1 | 73 | | if (ps.HadErrors || ps.Streams.Error.Count != 0 || |
| | 1 | 74 | | ps.Streams.Warning.Count > 0 || ps.Streams.Verbose.Count > 0 || |
| | 1 | 75 | | ps.Streams.Debug.Count > 0 || ps.Streams.Information.Count > 0) |
| | 4 | 76 | | { |
| | 0 | 77 | | config.Log.Verbose(BuildError.Text(ps)); |
| | 4 | 78 | | } |
| | 4 | 79 | | |
| | 1 | 80 | | return output; |
| | 4 | 81 | | } |
| | 4 | 82 | | finally |
| | 4 | 83 | | { |
| | 4 | 84 | | config.Pool.Release(runspace); |
| | 4 | 85 | | } |
| | 5 | 86 | | }; |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | private static Func<CancellationToken, Task<object?>> CSharpTask(TaskJobConfig config) |
| | | 90 | | { |
| | | 91 | | // Prepare locals upfront and include TaskProgress so compilation preamble declares it |
| | 10 | 92 | | var compileLocals = config.ScriptCode.Arguments is { Count: > 0 } |
| | 10 | 93 | | ? new Dictionary<string, object?>(config.ScriptCode.Arguments) |
| | 10 | 94 | | : []; |
| | 10 | 95 | | compileLocals["TaskProgress"] = config.Progress; |
| | | 96 | | |
| | | 97 | | // Compile and get a runner that returns object? (last expression) |
| | 10 | 98 | | var script = CSharpDelegateBuilder.Compile( |
| | 10 | 99 | | config.ScriptCode.Code, |
| | 10 | 100 | | config.Log, |
| | 10 | 101 | | config.ScriptCode.ExtraImports, |
| | 10 | 102 | | config.ScriptCode.ExtraRefs, |
| | 10 | 103 | | compileLocals, |
| | 10 | 104 | | config.ScriptCode.LanguageVersion); |
| | 10 | 105 | | var runner = script.CreateDelegate(); // ScriptRunner<object?> |
| | 10 | 106 | | return async ct => |
| | 10 | 107 | | { |
| | 10 | 108 | | // Use the same locals at execution time |
| | 7 | 109 | | var globals = new CsGlobals(SharedStateStore.Snapshot(), compileLocals); |
| | 7 | 110 | | return await runner(globals, ct).ConfigureAwait(false); |
| | 17 | 111 | | }; |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | private static Func<CancellationToken, Task<object?>> VbNetTask(TaskJobConfig config) |
| | | 115 | | { |
| | 1 | 116 | | var code = config.ScriptCode.Code; |
| | 1 | 117 | | var log = config.Log; |
| | 1 | 118 | | var extraImports = config.ScriptCode.ExtraImports; |
| | 1 | 119 | | var extraRefs = config.ScriptCode.ExtraRefs; |
| | 1 | 120 | | var arguments = config.ScriptCode.Arguments; |
| | 1 | 121 | | var vbLangVersion = Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16_9; |
| | 1 | 122 | | var runner = VBNetDelegateBuilder.Compile<object>( |
| | 1 | 123 | | code, |
| | 1 | 124 | | log, |
| | 1 | 125 | | extraImports, |
| | 1 | 126 | | extraRefs, |
| | 1 | 127 | | arguments, |
| | 1 | 128 | | vbLangVersion |
| | 1 | 129 | | ); |
| | 1 | 130 | | return async ct => |
| | 1 | 131 | | { |
| | 1 | 132 | | // For VB, expose Progress via locals as well |
| | 1 | 133 | | var locals = config.ScriptCode.Arguments is { Count: > 0 } |
| | 1 | 134 | | ? new Dictionary<string, object?>(config.ScriptCode.Arguments) |
| | 1 | 135 | | : []; |
| | 1 | 136 | | locals["TaskProgress"] = config.Progress; |
| | 1 | 137 | | var globals = new CsGlobals(SharedStateStore.Snapshot(), locals); |
| | 1 | 138 | | // VB compiled delegate does not accept CancellationToken; allow cooperative cancel of awaiting. |
| | 1 | 139 | | var task = runner(globals); |
| | 1 | 140 | | var completed = await Task.WhenAny(task, Task.Delay(Timeout.Infinite, ct)).ConfigureAwait(false); |
| | 1 | 141 | | if (completed == task) |
| | 1 | 142 | | { |
| | 1 | 143 | | return await task.ConfigureAwait(false); |
| | 1 | 144 | | } |
| | 0 | 145 | | ct.ThrowIfCancellationRequested(); |
| | 0 | 146 | | return null; // unreachable |
| | 2 | 147 | | }; |
| | | 148 | | } |
| | | 149 | | } |