| | | 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 | | { |
| | 141 | 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 | | /// Track all runspaces ever created (for cleanup) |
| | | 20 | | /// </summary> |
| | | 21 | | private readonly ConcurrentDictionary<Runspace, byte> _all; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// KestrunHost is needed for logging, config, etc. |
| | | 25 | | /// </summary> |
| | 2489 | 26 | | public KestrunHost Host { get; private set; } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Gets the minimum number of runspaces maintained in the pool. |
| | | 30 | | /// </summary> |
| | 2 | 31 | | public int MinRunspaces { get; } |
| | | 32 | | /// <summary> |
| | | 33 | | /// Gets the maximum number of runspaces allowed in the pool. |
| | | 34 | | /// </summary> |
| | 104 | 35 | | public int MaxRunspaces { get; } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Path to the OpenAPI class definitions to be injected into each runspace. |
| | | 39 | | /// </summary> |
| | 213 | 40 | | public string? OpenApiClassesPath { get; init; } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Thread‑affinity strategy for *future* runspaces. |
| | | 44 | | /// Default is <see cref="PSThreadOptions.ReuseThread"/>. |
| | | 45 | | /// </summary> |
| | 588 | 46 | | public PSThreadOptions ThreadOptions { get; set; } = PSThreadOptions.ReuseThread; |
| | | 47 | | |
| | | 48 | | // ───────────────── constructor ────────────────────────── |
| | | 49 | | /// <summary> |
| | | 50 | | /// Initializes a new instance of the <see cref="KestrunRunspacePoolManager"/> class with the specified minimum and |
| | | 51 | | /// </summary> |
| | | 52 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 53 | | /// <param name="minRunspaces">The minimum number of runspaces to maintain in the pool.</param> |
| | | 54 | | /// <param name="maxRunspaces">The maximum number of runspaces allowed in the pool.</param> |
| | | 55 | | /// <param name="initialSessionState">The initial session state for each runspace (optional).</param> |
| | | 56 | | /// <param name="threadOptions">The thread affinity strategy for runspaces (optional).</param> |
| | | 57 | | /// <param name="openApiClassesPath">The file path to the OpenAPI class definitions to be injected into each runspac |
| | 141 | 58 | | public KestrunRunspacePoolManager( |
| | 141 | 59 | | KestrunHost host, |
| | 141 | 60 | | int minRunspaces, |
| | 141 | 61 | | int maxRunspaces, |
| | 141 | 62 | | InitialSessionState? initialSessionState = null, |
| | 141 | 63 | | PSThreadOptions threadOptions = PSThreadOptions.ReuseThread, |
| | 141 | 64 | | string? openApiClassesPath = null) |
| | | 65 | | { |
| | 141 | 66 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 67 | | { |
| | 118 | 68 | | host.Logger.Debug("Initializing RunspacePoolManager: Min={Min}, Max={Max}", minRunspaces, maxRunspaces); |
| | | 69 | | } |
| | | 70 | | |
| | 140 | 71 | | ArgumentOutOfRangeException.ThrowIfNegative(minRunspaces); |
| | 139 | 72 | | ArgumentNullException.ThrowIfNull(host); |
| | 139 | 73 | | ArgumentOutOfRangeException.ThrowIfNegative(maxRunspaces); |
| | | 74 | | // sanity check |
| | 138 | 75 | | if (maxRunspaces < 1 || maxRunspaces < minRunspaces) |
| | | 76 | | { |
| | 2 | 77 | | throw new ArgumentOutOfRangeException(nameof(maxRunspaces)); |
| | | 78 | | } |
| | 136 | 79 | | _all = new(); |
| | 136 | 80 | | Host = host; |
| | 136 | 81 | | MinRunspaces = minRunspaces; |
| | 136 | 82 | | MaxRunspaces = maxRunspaces; |
| | 136 | 83 | | _iss = initialSessionState ?? InitialSessionState.CreateDefault(); |
| | 136 | 84 | | ThreadOptions = threadOptions; |
| | | 85 | | |
| | | 86 | | // warm the stash |
| | 536 | 87 | | for (var i = 0; i < minRunspaces; i++) |
| | | 88 | | { |
| | 132 | 89 | | _stash.Add(CreateRunspace()); |
| | | 90 | | } |
| | | 91 | | |
| | 136 | 92 | | _count = minRunspaces; |
| | | 93 | | |
| | | 94 | | // Store OpenAPI classes |
| | 136 | 95 | | OpenApiClassesPath = openApiClassesPath; |
| | 136 | 96 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 97 | | { |
| | 114 | 98 | | Host.Logger.Debug("Warm-started pool with {Count} runspaces", _count); |
| | | 99 | | } |
| | 136 | 100 | | } |
| | | 101 | | |
| | | 102 | | // ───────────────── public API ──────────────────────────── |
| | | 103 | | /// <summary>Borrow a runspace (creates one if under the cap).</summary> |
| | | 104 | | public Runspace Acquire() |
| | | 105 | | { |
| | 67 | 106 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 107 | | { |
| | 67 | 108 | | Host.Logger.Debug("Acquiring runspace from pool: CurrentCount={Count}, Max={Max}", _count, MaxRunspaces); |
| | | 109 | | } |
| | | 110 | | |
| | 67 | 111 | | ObjectDisposedException.ThrowIf(_disposed, nameof(KestrunRunspacePoolManager)); |
| | | 112 | | |
| | 66 | 113 | | if (_stash.TryTake(out var rs)) |
| | | 114 | | { |
| | 43 | 115 | | if (rs.RunspaceStateInfo.State != RunspaceState.Opened) |
| | | 116 | | { |
| | 0 | 117 | | Host.Logger.Warning("Runspace from stash is not opened: {State}. Discarding and acquiring a new one.", r |
| | | 118 | | // If the runspace is not open, we cannot use it. |
| | | 119 | | // Discard and try again |
| | 0 | 120 | | rs.Dispose(); |
| | 0 | 121 | | _ = Interlocked.Decrement(ref _count); |
| | 0 | 122 | | return Acquire(); |
| | | 123 | | } |
| | 43 | 124 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 125 | | { |
| | 43 | 126 | | Host.Logger.Debug("Reusing runspace from stash: StashCount={Count}", _stash.Count); |
| | | 127 | | } |
| | | 128 | | |
| | 43 | 129 | | return rs; |
| | | 130 | | } |
| | | 131 | | // Need a new one?—but only if we haven’t reached max. |
| | 23 | 132 | | if (Interlocked.Increment(ref _count) <= MaxRunspaces) |
| | | 133 | | { |
| | 22 | 134 | | Host.Logger.Debug("Creating new runspace: TotalCount={Count}", _count); |
| | 22 | 135 | | return CreateRunspace(); |
| | | 136 | | } |
| | | 137 | | // Overshot: roll back and complain. |
| | 1 | 138 | | _ = Interlocked.Decrement(ref _count); |
| | | 139 | | |
| | 1 | 140 | | Host.Logger.Warning("Runspace limit reached: Max={Max}", MaxRunspaces); |
| | 1 | 141 | | throw new InvalidOperationException("Run-space limit reached."); |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Asynchronously acquires a runspace from the pool, creating a new one if under the cap, or waits until one become |
| | | 146 | | /// </summary> |
| | | 147 | | /// <param name="cancellationToken">A cancellation token to observe while waiting for a runspace.</param> |
| | | 148 | | /// <returns>A task that represents the asynchronous operation, containing the acquired <see cref="Runspace"/>.</ret |
| | | 149 | | public async Task<Runspace> AcquireAsync(CancellationToken cancellationToken = default) |
| | | 150 | | { |
| | 7 | 151 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 152 | | { |
| | 4 | 153 | | Host.Logger.Debug("Acquiring runspace (async) from pool: CurrentCount={Count}, Max={Max}", _count, MaxRunspa |
| | | 154 | | } |
| | | 155 | | |
| | 2 | 156 | | while (true) |
| | | 157 | | { |
| | 9 | 158 | | ObjectDisposedException.ThrowIf(_disposed, nameof(KestrunRunspacePoolManager)); |
| | | 159 | | |
| | 8 | 160 | | if (_stash.TryTake(out var rs)) |
| | | 161 | | { |
| | 5 | 162 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 163 | | { |
| | 2 | 164 | | Host.Logger.Debug("Reusing runspace from stash (async): StashCount={Count}", _stash.Count); |
| | | 165 | | } |
| | | 166 | | |
| | 5 | 167 | | return rs; |
| | | 168 | | } |
| | | 169 | | // Need a new one?—but only if we haven’t reached max. |
| | 3 | 170 | | if (Interlocked.Increment(ref _count) <= MaxRunspaces) |
| | | 171 | | { |
| | 0 | 172 | | Host.Logger.Debug("Creating new runspace (async): TotalCount={Count}", _count); |
| | | 173 | | // Runspace creation is synchronous, but we can offload to thread pool |
| | 0 | 174 | | return await Task.Run(CreateRunspace, cancellationToken).ConfigureAwait(false); |
| | | 175 | | } |
| | | 176 | | // Overshot: roll back and try again. |
| | 3 | 177 | | _ = Interlocked.Decrement(ref _count); |
| | | 178 | | |
| | | 179 | | // Wait for a runspace to be returned |
| | 3 | 180 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 181 | | { |
| | 3 | 182 | | Host.Logger.Debug("Waiting for runspace to become available (async)"); |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | // Use a short delay to poll for availability |
| | 3 | 186 | | await Task.Delay(50, cancellationToken).ConfigureAwait(false); |
| | | 187 | | } |
| | 5 | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Returns a runspace to the pool for reuse, or disposes it if the pool has been disposed. |
| | | 192 | | /// </summary> |
| | | 193 | | /// <param name="rs">The <see cref="Runspace"/> to return to the pool.</param> |
| | | 194 | | public void Release(Runspace rs) |
| | | 195 | | { |
| | 66 | 196 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 197 | | { |
| | 65 | 198 | | Host.Logger.Debug("Release() called: Disposed={Disposed}", _disposed); |
| | | 199 | | } |
| | | 200 | | |
| | 66 | 201 | | if (_disposed) |
| | | 202 | | { |
| | 1 | 203 | | Host.Logger.Warning("Pool disposed; disposing returned runspace"); |
| | 1 | 204 | | rs.Dispose(); |
| | 1 | 205 | | return; |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | try |
| | | 209 | | { |
| | | 210 | | // Put the genie back in the bottle: variables, funcs, modules… |
| | | 211 | | // This returns the runspace to the InitialSessionState baseline. |
| | 65 | 212 | | rs.ResetRunspaceState(); |
| | 65 | 213 | | } |
| | 0 | 214 | | catch (Exception ex) |
| | | 215 | | { |
| | 0 | 216 | | Host.Logger.Warning(ex, "ResetRunspaceState failed; disposing runspace instead"); |
| | 0 | 217 | | try { rs.Close(); } |
| | 0 | 218 | | catch (Exception closeEx) { Host.Logger.Verbose(exception: closeEx, messageTemplate: "Failed to close runspa |
| | 0 | 219 | | rs.Dispose(); |
| | 0 | 220 | | _ = Interlocked.Decrement(ref _count); |
| | 0 | 221 | | return; |
| | | 222 | | } |
| | 65 | 223 | | _stash.Add(rs); |
| | 65 | 224 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 225 | | { |
| | 64 | 226 | | Host.Logger.Debug("Runspace returned to stash: StashCount={Count}", _stash.Count); |
| | | 227 | | } |
| | | 228 | | // Note: we do not decrement _count here, as the pool size is fixed. |
| | | 229 | | // The pool will keep the runspace open for reuse. |
| | 65 | 230 | | } |
| | | 231 | | |
| | | 232 | | // ───────────────── helpers ─────────────────────────────── |
| | | 233 | | /// <summary> |
| | | 234 | | /// Creates a new PowerShell runspace with the configured initial session state and thread options. |
| | | 235 | | /// </summary> |
| | | 236 | | /// <returns>A new <see cref="Runspace"/> instance.</returns> |
| | | 237 | | private Runspace CreateRunspace() |
| | | 238 | | { |
| | 154 | 239 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 240 | | { |
| | 132 | 241 | | Host.Logger.Debug("CreateRunspace() - creating new runspace"); |
| | | 242 | | } |
| | | 243 | | |
| | 154 | 244 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 245 | | { |
| | 132 | 246 | | Host.Logger.Debug("Creating new runspace with InitialSessionState"); |
| | | 247 | | } |
| | | 248 | | // Important: clone per runspace |
| | 154 | 249 | | var iss = _iss.Clone(); |
| | 154 | 250 | | var rs = RunspaceFactory.CreateRunspace(iss); |
| | | 251 | | |
| | | 252 | | // Apply the chosen thread‑affinity strategy **before** opening. |
| | 154 | 253 | | rs.ThreadOptions = ThreadOptions; |
| | 154 | 254 | | rs.ApartmentState = ApartmentState.MTA; // always MTA |
| | 154 | 255 | | rs.Open(); |
| | | 256 | | |
| | 154 | 257 | | Host.Logger.Information("Opened new Runspace with ThreadOptions={ThreadOptions}", ThreadOptions); |
| | 154 | 258 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 259 | | { |
| | 132 | 260 | | Host.Logger.Debug("New runspace created: {Runspace}", rs); |
| | | 261 | | } |
| | | 262 | | |
| | 154 | 263 | | _ = _all.TryAdd(rs, 0); |
| | 154 | 264 | | return rs; |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | // ───────────────── cleanup ─────────────────────────────── |
| | | 268 | | /// <summary> |
| | | 269 | | /// Disposes the runspace pool manager and all pooled runspaces. |
| | | 270 | | /// </summary> |
| | | 271 | | public void Dispose() |
| | | 272 | | { |
| | 91 | 273 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 274 | | { |
| | 89 | 275 | | Host.Logger.Debug("Disposing KestrunRunspacePoolManager: Disposed={Disposed}", _disposed); |
| | | 276 | | } |
| | | 277 | | |
| | 91 | 278 | | if (_disposed) |
| | | 279 | | { |
| | 20 | 280 | | return; |
| | | 281 | | } |
| | | 282 | | |
| | 71 | 283 | | if (!string.IsNullOrWhiteSpace(OpenApiClassesPath)) |
| | | 284 | | { |
| | | 285 | | try |
| | | 286 | | { |
| | 2 | 287 | | File.Delete(OpenApiClassesPath); |
| | 0 | 288 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 289 | | { |
| | 0 | 290 | | Host.Logger.Debug("Deleted temporary OpenAPI classes script: {Path}", OpenApiClassesPath); |
| | | 291 | | } |
| | 0 | 292 | | } |
| | 2 | 293 | | catch (Exception ex) |
| | | 294 | | { |
| | 2 | 295 | | Host.Logger.Warning(ex, "Failed to delete temporary OpenAPI classes script: {Path}", OpenApiClassesPath) |
| | 2 | 296 | | } |
| | | 297 | | } |
| | 71 | 298 | | _disposed = true; |
| | | 299 | | |
| | 71 | 300 | | Host.Logger.Information("Disposing RunspacePoolManager and all pooled runspaces"); |
| | | 301 | | |
| | | 302 | | // Drain the stash |
| | 157 | 303 | | while (_stash.TryTake(out var rs)) |
| | | 304 | | { |
| | 86 | 305 | | if (Host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 306 | | { |
| | 84 | 307 | | Host.Logger.Debug("Disposing runspace: {Runspace}", rs); |
| | | 308 | | } |
| | 172 | 309 | | try { rs.ResetRunspaceState(); } catch (Exception ex) { Host.Logger.Verbose(exception: ex, messageTemplate: |
| | 172 | 310 | | try { rs.Close(); } catch (Exception ex) { Host.Logger.Verbose(exception: ex, messageTemplate: "Failed to cl |
| | 86 | 311 | | rs.Dispose(); |
| | 86 | 312 | | _ = _all.TryRemove(rs, out _); |
| | 86 | 313 | | _ = Interlocked.Decrement(ref _count); |
| | 86 | 314 | | } |
| | | 315 | | |
| | | 316 | | // Anything still checked out? Close them too. |
| | 148 | 317 | | foreach (var kv in _all.Keys) |
| | | 318 | | { |
| | 6 | 319 | | try { kv.ResetRunspaceState(); } catch (Exception ex) { Host.Logger.Verbose(exception: ex, messageTemplate: |
| | 6 | 320 | | try { kv.Close(); } catch (Exception ex) { Host.Logger.Verbose(exception: ex, messageTemplate: "Failed to cl |
| | 3 | 321 | | kv.Dispose(); |
| | 3 | 322 | | _ = _all.TryRemove(kv, out _); |
| | 3 | 323 | | _ = Interlocked.Decrement(ref _count); |
| | | 324 | | } |
| | 71 | 325 | | Host.Logger.Information("RunspacePoolManager disposed"); |
| | 71 | 326 | | } |
| | | 327 | | } |