| | 1 | | using System.Collections.Concurrent; |
| | 2 | | using System.Management.Automation.Runspaces; |
| | 3 | | using Serilog; |
| | 4 | | using Serilog.Events; |
| | 5 | |
|
| | 6 | | namespace Kestrun.Scripting; |
| | 7 | |
|
| | 8 | | /// <summary> |
| | 9 | | /// Manages a pool of PowerShell runspaces for efficient reuse and resource control. |
| | 10 | | /// </summary> |
| | 11 | | public sealed class KestrunRunspacePoolManager : IDisposable |
| | 12 | | { |
| 50 | 13 | | private readonly ConcurrentBag<Runspace> _stash = []; |
| | 14 | | private readonly InitialSessionState _iss; |
| | 15 | | private int _count; // total live runspaces |
| | 16 | | private bool _disposed; |
| | 17 | |
|
| | 18 | | /// <summary> |
| | 19 | | /// Gets the minimum number of runspaces maintained in the pool. |
| | 20 | | /// </summary> |
| 0 | 21 | | public int MinRunspaces { get; } |
| | 22 | | /// <summary> |
| | 23 | | /// Gets the maximum number of runspaces allowed in the pool. |
| | 24 | | /// </summary> |
| 16 | 25 | | public int MaxRunspaces { get; } |
| | 26 | |
|
| | 27 | | /// <summary> |
| | 28 | | /// Thread‑affinity strategy for *future* runspaces. |
| | 29 | | /// Default is <see cref="PSThreadOptions.ReuseThread"/>. |
| | 30 | | /// </summary> |
| 198 | 31 | | public PSThreadOptions ThreadOptions { get; set; } = PSThreadOptions.ReuseThread; |
| | 32 | |
|
| | 33 | | // ───────────────── constructor ────────────────────────── |
| | 34 | | /// <summary> |
| | 35 | | /// Initializes a new instance of the <see cref="KestrunRunspacePoolManager"/> class with the specified minimum and |
| | 36 | | /// </summary> |
| | 37 | | /// <param name="minRunspaces">The minimum number of runspaces to maintain in the pool.</param> |
| | 38 | | /// <param name="maxRunspaces">The maximum number of runspaces allowed in the pool.</param> |
| | 39 | | /// <param name="initialSessionState">The initial session state for each runspace (optional).</param> |
| | 40 | | /// <param name="threadOptions">The thread affinity strategy for runspaces (optional).</param> |
| 50 | 41 | | public KestrunRunspacePoolManager( |
| 50 | 42 | | int minRunspaces, |
| 50 | 43 | | int maxRunspaces, |
| 50 | 44 | | InitialSessionState? initialSessionState = null, |
| 50 | 45 | | PSThreadOptions threadOptions = PSThreadOptions.ReuseThread) |
| | 46 | | { |
| 50 | 47 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 48 | | { |
| 50 | 49 | | Log.Debug("Initializing RunspacePoolManager: Min={Min}, Max={Max}", minRunspaces, maxRunspaces); |
| | 50 | | } |
| | 51 | |
|
| 50 | 52 | | ArgumentOutOfRangeException.ThrowIfNegative(minRunspaces); |
| 50 | 53 | | if (maxRunspaces < 1 || maxRunspaces < minRunspaces) |
| | 54 | | { |
| 0 | 55 | | throw new ArgumentOutOfRangeException(nameof(maxRunspaces)); |
| | 56 | | } |
| | 57 | |
|
| 50 | 58 | | MinRunspaces = minRunspaces; |
| 50 | 59 | | MaxRunspaces = maxRunspaces; |
| 50 | 60 | | _iss = initialSessionState ?? InitialSessionState.CreateDefault(); |
| 50 | 61 | | ThreadOptions = threadOptions; |
| | 62 | |
|
| | 63 | | // warm the stash |
| 198 | 64 | | for (var i = 0; i < minRunspaces; i++) |
| | 65 | | { |
| 49 | 66 | | _stash.Add(CreateRunspace()); |
| | 67 | | } |
| | 68 | |
|
| 50 | 69 | | _count = minRunspaces; |
| 50 | 70 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 71 | | { |
| 50 | 72 | | Log.Debug("Warm-started pool with {Count} runspaces", _count); |
| | 73 | | } |
| 50 | 74 | | } |
| | 75 | |
|
| | 76 | | // ───────────────── public API ──────────────────────────── |
| | 77 | | /// <summary>Borrow a runspace (creates one if under the cap).</summary> |
| | 78 | | public Runspace Acquire() |
| | 79 | | { |
| 11 | 80 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 81 | | { |
| 11 | 82 | | Log.Debug("Acquiring runspace from pool: CurrentCount={Count}, Max={Max}", _count, MaxRunspaces); |
| | 83 | | } |
| | 84 | |
|
| 11 | 85 | | ObjectDisposedException.ThrowIf(_disposed, nameof(KestrunRunspacePoolManager)); |
| | 86 | |
|
| 11 | 87 | | if (_stash.TryTake(out var rs)) |
| | 88 | | { |
| 11 | 89 | | if (rs.RunspaceStateInfo.State != RunspaceState.Opened) |
| | 90 | | { |
| 0 | 91 | | Log.Warning("Runspace from stash is not opened: {State}. Discarding and acquiring a new one.", rs.Runspa |
| | 92 | | // If the runspace is not open, we cannot use it. |
| | 93 | | // Discard and try again |
| 0 | 94 | | rs.Dispose(); |
| 0 | 95 | | _ = Interlocked.Decrement(ref _count); |
| 0 | 96 | | return Acquire(); |
| | 97 | | } |
| 11 | 98 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 99 | | { |
| 11 | 100 | | Log.Debug("Reusing runspace from stash: StashCount={Count}", _stash.Count); |
| | 101 | | } |
| | 102 | |
|
| 11 | 103 | | return rs; |
| | 104 | | } |
| | 105 | | // Need a new one?—but only if we haven’t reached max. |
| 0 | 106 | | if (Interlocked.Increment(ref _count) <= MaxRunspaces) |
| | 107 | | { |
| 0 | 108 | | Log.Debug("Creating new runspace: TotalCount={Count}", _count); |
| 0 | 109 | | return CreateRunspace(); |
| | 110 | | } |
| | 111 | | // Overshot: roll back and complain. |
| 0 | 112 | | _ = Interlocked.Decrement(ref _count); |
| | 113 | |
|
| 0 | 114 | | Log.Warning("Runspace limit reached: Max={Max}", MaxRunspaces); |
| 0 | 115 | | throw new InvalidOperationException("Run-space limit reached."); |
| | 116 | | } |
| | 117 | |
|
| | 118 | | /// <summary> |
| | 119 | | /// Asynchronously acquires a runspace from the pool, creating a new one if under the cap, or waits until one become |
| | 120 | | /// </summary> |
| | 121 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for a runspace.</param> |
| | 122 | | /// <returns>A task that represents the asynchronous operation, containing the acquired <see cref="Runspace"/>.</ret |
| | 123 | | public async Task<Runspace> AcquireAsync(CancellationToken cancellationToken = default) |
| | 124 | | { |
| 4 | 125 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 126 | | { |
| 4 | 127 | | Log.Debug("Acquiring runspace (async) from pool: CurrentCount={Count}, Max={Max}", _count, MaxRunspaces); |
| | 128 | | } |
| | 129 | |
|
| 0 | 130 | | while (true) |
| | 131 | | { |
| 4 | 132 | | ObjectDisposedException.ThrowIf(_disposed, nameof(KestrunRunspacePoolManager)); |
| | 133 | |
|
| 3 | 134 | | if (_stash.TryTake(out var rs)) |
| | 135 | | { |
| 3 | 136 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 137 | | { |
| 3 | 138 | | Log.Debug("Reusing runspace from stash (async): StashCount={Count}", _stash.Count); |
| | 139 | | } |
| | 140 | |
|
| 3 | 141 | | return rs; |
| | 142 | | } |
| | 143 | |
|
| 0 | 144 | | if (Interlocked.Increment(ref _count) <= MaxRunspaces) |
| | 145 | | { |
| 0 | 146 | | Log.Debug("Creating new runspace (async): TotalCount={Count}", _count); |
| | 147 | | // Runspace creation is synchronous, but we can offload to thread pool |
| 0 | 148 | | return await Task.Run(CreateRunspace, cancellationToken).ConfigureAwait(false); |
| | 149 | | } |
| 0 | 150 | | _ = Interlocked.Decrement(ref _count); |
| | 151 | |
|
| | 152 | | // Wait for a runspace to be returned |
| 0 | 153 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 154 | | { |
| 0 | 155 | | Log.Debug("Waiting for runspace to become available (async)"); |
| | 156 | | } |
| | 157 | |
|
| | 158 | | // Use a short delay to poll for availability |
| 0 | 159 | | await Task.Delay(50, cancellationToken).ConfigureAwait(false); |
| | 160 | | } |
| 3 | 161 | | } |
| | 162 | |
|
| | 163 | |
|
| | 164 | | /// <summary> |
| | 165 | | /// Returns a runspace to the pool for reuse, or disposes it if the pool has been disposed. |
| | 166 | | /// </summary> |
| | 167 | | /// <param name="rs">The <see cref="Runspace"/> to return to the pool.</param> |
| | 168 | | public void Release(Runspace rs) |
| | 169 | | { |
| 14 | 170 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 171 | | { |
| 14 | 172 | | Log.Debug("Release() called: Disposed={Disposed}", _disposed); |
| | 173 | | } |
| | 174 | |
|
| 14 | 175 | | if (_disposed) |
| | 176 | | { |
| 0 | 177 | | Log.Warning("Pool disposed; disposing returned runspace"); |
| 0 | 178 | | rs.Dispose(); |
| 0 | 179 | | return; |
| | 180 | | } |
| | 181 | |
|
| 14 | 182 | | _stash.Add(rs); |
| 14 | 183 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 184 | | { |
| 14 | 185 | | Log.Debug("Runspace returned to stash: StashCount={Count}", _stash.Count); |
| | 186 | | } |
| | 187 | | // Note: we do not decrement _count here, as the pool size is fixed. |
| | 188 | | // The pool will keep the runspace open for reuse. |
| 14 | 189 | | } |
| | 190 | |
|
| | 191 | |
|
| | 192 | | // ───────────────── helpers ─────────────────────────────── |
| | 193 | | private Runspace CreateRunspace() |
| | 194 | | { |
| 49 | 195 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 196 | | { |
| 49 | 197 | | Log.Debug("CreateRunspace() - creating new runspace"); |
| | 198 | | } |
| | 199 | |
|
| 49 | 200 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 201 | | { |
| 49 | 202 | | Log.Debug("Creating new runspace with InitialSessionState: {Iss}", _iss); |
| | 203 | | } |
| | 204 | |
|
| 49 | 205 | | var rs = RunspaceFactory.CreateRunspace(_iss); |
| | 206 | |
|
| | 207 | | // Apply the chosen thread‑affinity strategy **before** opening. |
| 49 | 208 | | rs.ThreadOptions = ThreadOptions; |
| 49 | 209 | | rs.ApartmentState = ApartmentState.MTA; // always MTA |
| | 210 | |
|
| 49 | 211 | | rs.Open(); |
| 49 | 212 | | Log.Information("Opened new Runspace with ThreadOptions={ThreadOptions}", ThreadOptions); |
| 49 | 213 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 214 | | { |
| 49 | 215 | | Log.Debug("New runspace created: {Runspace}", rs); |
| | 216 | | } |
| | 217 | |
|
| 49 | 218 | | return rs; |
| | 219 | | } |
| | 220 | |
|
| | 221 | | // ───────────────── cleanup ─────────────────────────────── |
| | 222 | | /// <summary> |
| | 223 | | /// Disposes the runspace pool manager and all pooled runspaces. |
| | 224 | | /// </summary> |
| | 225 | | public void Dispose() |
| | 226 | | { |
| 38 | 227 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 228 | | { |
| 38 | 229 | | Log.Debug("Disposing KestrunRunspacePoolManager: Disposed={Disposed}", _disposed); |
| | 230 | | } |
| | 231 | |
|
| 38 | 232 | | if (_disposed) |
| | 233 | | { |
| 17 | 234 | | return; |
| | 235 | | } |
| | 236 | |
|
| 21 | 237 | | _disposed = true; |
| 21 | 238 | | Log.Information("Disposing RunspacePoolManager and all pooled runspaces"); |
| 41 | 239 | | while (_stash.TryTake(out var rs)) |
| | 240 | | { |
| 20 | 241 | | if (Log.IsEnabled(LogEventLevel.Debug)) |
| | 242 | | { |
| 20 | 243 | | Log.Debug("Disposing runspace: {Runspace}", rs); |
| | 244 | | } |
| | 245 | |
|
| 40 | 246 | | try { rs.Close(); } catch { /* ignore */ } |
| 20 | 247 | | rs.Dispose(); |
| 20 | 248 | | } |
| 21 | 249 | | Log.Information("RunspacePoolManager disposed"); |
| 21 | 250 | | } |
| | 251 | | } |