|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Management.Automation.Runspaces; |
| 4 | +using System.Reflection; |
| 5 | +using System.Text; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using System.Threading; |
| 8 | + |
| 9 | +namespace Microsoft.PowerShell.EditorServices.Session |
| 10 | +{ |
| 11 | + using System.Management.Automation; |
| 12 | + |
| 13 | + /// <summary> |
| 14 | + /// Provides the ability to take over the current pipeline in a runspace. |
| 15 | + /// </summary> |
| 16 | + internal class InvocationEventQueue |
| 17 | + { |
| 18 | + private readonly PromptNest _promptNest; |
| 19 | + private readonly Runspace _runspace; |
| 20 | + private readonly PowerShellContext _powerShellContext; |
| 21 | + private InvocationRequest _invocationRequest; |
| 22 | + private Task _currentWaitTask; |
| 23 | + private SemaphoreSlim _lock = new SemaphoreSlim(1, 1); |
| 24 | + |
| 25 | + internal InvocationEventQueue(PowerShellContext powerShellContext, PromptNest promptNest) |
| 26 | + { |
| 27 | + _promptNest = promptNest; |
| 28 | + _powerShellContext = powerShellContext; |
| 29 | + _runspace = powerShellContext.CurrentRunspace.Runspace; |
| 30 | + CreateInvocationSubscriber(); |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Executes a command on the main pipeline thread through |
| 35 | + /// eventing. A <see cref="PSEngineEvent.OnIdle" /> event subscriber will |
| 36 | + /// be created that creates a nested PowerShell instance for |
| 37 | + /// <see cref="PowerShellContext.ExecuteCommand" /> to utilize. |
| 38 | + /// </summary> |
| 39 | + /// <remarks> |
| 40 | + /// Avoid using this method directly if possible. |
| 41 | + /// <see cref="PowerShellContext.ExecuteCommand" /> will route commands |
| 42 | + /// through this method if required. |
| 43 | + /// </remarks> |
| 44 | + /// <typeparam name="TResult">The expected result type.</typeparam> |
| 45 | + /// <param name="psCommand">The <see cref="PSCommand" /> to be executed.</param> |
| 46 | + /// <param name="errorMessages"> |
| 47 | + /// Error messages from PowerShell will be written to the <see cref="StringBuilder" />. |
| 48 | + /// </param> |
| 49 | + /// <param name="executionOptions">Specifies options to be used when executing this command.</param> |
| 50 | + /// <returns> |
| 51 | + /// An awaitable <see cref="Task" /> which will provide results once the command |
| 52 | + /// execution completes. |
| 53 | + /// </returns> |
| 54 | + internal async Task<IEnumerable<TResult>> ExecuteCommandOnIdle<TResult>( |
| 55 | + PSCommand psCommand, |
| 56 | + StringBuilder errorMessages, |
| 57 | + ExecutionOptions executionOptions) |
| 58 | + { |
| 59 | + var request = new PipelineExecutionRequest<TResult>( |
| 60 | + _powerShellContext, |
| 61 | + psCommand, |
| 62 | + errorMessages, |
| 63 | + executionOptions); |
| 64 | + |
| 65 | + await SetInvocationRequestAsync( |
| 66 | + new InvocationRequest( |
| 67 | + pwsh => request.Execute().GetAwaiter().GetResult())); |
| 68 | + |
| 69 | + try |
| 70 | + { |
| 71 | + return await request.Results; |
| 72 | + } |
| 73 | + finally |
| 74 | + { |
| 75 | + await SetInvocationRequestAsync(null); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Marshals a <see cref="Action{PowerShell}" /> to run on the pipeline thread. A new |
| 81 | + /// <see cref="PromptNestFrame" /> will be created for the invocation. |
| 82 | + /// </summary> |
| 83 | + /// <param name="invocationAction"> |
| 84 | + /// The <see cref="Action{PowerShell}" /> to invoke on the pipeline thread. The nested |
| 85 | + /// <see cref="PowerShell" /> instance for the created <see cref="PromptNestFrame" /> |
| 86 | + /// will be passed as an argument. |
| 87 | + /// </param> |
| 88 | + /// <returns> |
| 89 | + /// An awaitable <see cref="Task" /> that the caller can use to know when execution completes. |
| 90 | + /// </returns> |
| 91 | + internal async Task InvokeOnPipelineThread(Action<PowerShell> invocationAction) |
| 92 | + { |
| 93 | + var request = new InvocationRequest(pwsh => |
| 94 | + { |
| 95 | + using (_promptNest.GetRunspaceHandle(CancellationToken.None, isReadLine: false)) |
| 96 | + { |
| 97 | + pwsh.Runspace = _runspace; |
| 98 | + invocationAction(pwsh); |
| 99 | + } |
| 100 | + }); |
| 101 | + |
| 102 | + await SetInvocationRequestAsync(request); |
| 103 | + try |
| 104 | + { |
| 105 | + await request.Task; |
| 106 | + } |
| 107 | + finally |
| 108 | + { |
| 109 | + await SetInvocationRequestAsync(null); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private async Task WaitForExistingRequestAsync() |
| 114 | + { |
| 115 | + InvocationRequest existingRequest; |
| 116 | + await _lock.WaitAsync(); |
| 117 | + try |
| 118 | + { |
| 119 | + existingRequest = _invocationRequest; |
| 120 | + if (existingRequest == null || existingRequest.Task.IsCompleted) |
| 121 | + { |
| 122 | + return; |
| 123 | + } |
| 124 | + } |
| 125 | + finally |
| 126 | + { |
| 127 | + _lock.Release(); |
| 128 | + } |
| 129 | + |
| 130 | + await existingRequest.Task; |
| 131 | + } |
| 132 | + |
| 133 | + private async Task SetInvocationRequestAsync(InvocationRequest request) |
| 134 | + { |
| 135 | + await WaitForExistingRequestAsync(); |
| 136 | + await _lock.WaitAsync(); |
| 137 | + try |
| 138 | + { |
| 139 | + _invocationRequest = request; |
| 140 | + } |
| 141 | + finally |
| 142 | + { |
| 143 | + _lock.Release(); |
| 144 | + } |
| 145 | + |
| 146 | + _powerShellContext.ForcePSEventHandling(); |
| 147 | + } |
| 148 | + |
| 149 | + private void OnPowerShellIdle(object sender, EventArgs e) |
| 150 | + { |
| 151 | + if (!_lock.Wait(0)) |
| 152 | + { |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + InvocationRequest currentRequest = null; |
| 157 | + try |
| 158 | + { |
| 159 | + if (_invocationRequest == null || System.Console.KeyAvailable) |
| 160 | + { |
| 161 | + return; |
| 162 | + } |
| 163 | + |
| 164 | + currentRequest = _invocationRequest; |
| 165 | + } |
| 166 | + finally |
| 167 | + { |
| 168 | + _lock.Release(); |
| 169 | + } |
| 170 | + |
| 171 | + _promptNest.PushPromptContext(); |
| 172 | + try |
| 173 | + { |
| 174 | + currentRequest.Invoke(_promptNest.GetPowerShell()); |
| 175 | + } |
| 176 | + finally |
| 177 | + { |
| 178 | + _promptNest.PopPromptContext(); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private PSEventSubscriber CreateInvocationSubscriber() |
| 183 | + { |
| 184 | + PSEventSubscriber subscriber = _runspace.Events.SubscribeEvent( |
| 185 | + source: null, |
| 186 | + eventName: PSEngineEvent.OnIdle, |
| 187 | + sourceIdentifier: PSEngineEvent.OnIdle, |
| 188 | + data: null, |
| 189 | + handlerDelegate: OnPowerShellIdle, |
| 190 | + supportEvent: true, |
| 191 | + forwardEvent: false); |
| 192 | + |
| 193 | + SetSubscriberExecutionThreadWithReflection(subscriber); |
| 194 | + |
| 195 | + subscriber.Unsubscribed += OnInvokerUnsubscribed; |
| 196 | + |
| 197 | + return subscriber; |
| 198 | + } |
| 199 | + |
| 200 | + private void OnInvokerUnsubscribed(object sender, PSEventUnsubscribedEventArgs e) |
| 201 | + { |
| 202 | + CreateInvocationSubscriber(); |
| 203 | + } |
| 204 | + |
| 205 | + private void SetSubscriberExecutionThreadWithReflection(PSEventSubscriber subscriber) |
| 206 | + { |
| 207 | + // We need to create the PowerShell object in the same thread so we can get a nested |
| 208 | + // PowerShell. Without changes to PSReadLine directly, this is the only way to achieve |
| 209 | + // that consistently. The alternative is to make the subscriber a script block and have |
| 210 | + // that create and process the PowerShell object, but that puts us in a different |
| 211 | + // SessionState and is a lot slower. |
| 212 | + |
| 213 | + // This should be safe as PSReadline should be waiting for pipeline input due to the |
| 214 | + // OnIdle event sent along with it. |
| 215 | + typeof(PSEventSubscriber) |
| 216 | + .GetProperty( |
| 217 | + "ShouldProcessInExecutionThread", |
| 218 | + BindingFlags.Instance | BindingFlags.NonPublic) |
| 219 | + .SetValue(subscriber, true); |
| 220 | + } |
| 221 | + |
| 222 | + private class InvocationRequest : TaskCompletionSource<bool> |
| 223 | + { |
| 224 | + private readonly Action<PowerShell> _invocationAction; |
| 225 | + |
| 226 | + internal InvocationRequest(Action<PowerShell> invocationAction) |
| 227 | + { |
| 228 | + _invocationAction = invocationAction; |
| 229 | + } |
| 230 | + |
| 231 | + internal void Invoke(PowerShell pwsh) |
| 232 | + { |
| 233 | + try |
| 234 | + { |
| 235 | + _invocationAction(pwsh); |
| 236 | + |
| 237 | + // Ensure the result is set in another thread otherwise the caller |
| 238 | + // may take over the pipeline thread. |
| 239 | + System.Threading.Tasks.Task.Run(() => SetResult(true)); |
| 240 | + } |
| 241 | + catch (Exception e) |
| 242 | + { |
| 243 | + System.Threading.Tasks.Task.Run(() => SetException(e)); |
| 244 | + } |
| 245 | + } |
| 246 | + } |
| 247 | + } |
| 248 | +} |
0 commit comments