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