| | | 1 | | using ConsoleLogStreaming.Core; |
| | | 2 | | using ConsoleLogStreaming.Core.Capture; |
| | | 3 | | using CShells.Lifecycle; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Diagnostics.ConsoleLogs.Services; |
| | | 7 | | |
| | | 8 | | public class ConsoleLogCaptureShellLease(IServiceProvider serviceProvider) |
| | | 9 | | { |
| | | 10 | | private readonly SemaphoreSlim _lock = new(1, 1); |
| | | 11 | | private bool _started; |
| | | 12 | | |
| | | 13 | | public async Task StartAsync(CancellationToken cancellationToken = default) |
| | | 14 | | { |
| | | 15 | | await _lock.WaitAsync(cancellationToken); |
| | | 16 | | try |
| | | 17 | | { |
| | | 18 | | if (_started) |
| | | 19 | | return; |
| | | 20 | | |
| | | 21 | | ConsoleLogStreamingHost.AddReference(); |
| | | 22 | | var releaseReference = true; |
| | | 23 | | |
| | | 24 | | try |
| | | 25 | | { |
| | | 26 | | var capture = serviceProvider.GetRequiredService<IConsoleLogCapture>(); |
| | | 27 | | await capture.StartAsync(cancellationToken); |
| | | 28 | | _started = true; |
| | | 29 | | releaseReference = false; |
| | | 30 | | } |
| | | 31 | | finally |
| | | 32 | | { |
| | | 33 | | if (releaseReference) |
| | | 34 | | await ConsoleLogStreamingHost.ReleaseReferenceAsync(CancellationToken.None); |
| | | 35 | | } |
| | | 36 | | } |
| | | 37 | | finally |
| | | 38 | | { |
| | | 39 | | _lock.Release(); |
| | | 40 | | } |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | public async Task StopAsync(CancellationToken cancellationToken = default) |
| | | 44 | | { |
| | | 45 | | await _lock.WaitAsync(cancellationToken); |
| | | 46 | | try |
| | | 47 | | { |
| | | 48 | | if (!_started) |
| | | 49 | | return; |
| | | 50 | | |
| | | 51 | | _started = false; |
| | | 52 | | await ConsoleLogStreamingHost.ReleaseReferenceAsync(cancellationToken); |
| | | 53 | | } |
| | | 54 | | finally |
| | | 55 | | { |
| | | 56 | | _lock.Release(); |
| | | 57 | | } |
| | | 58 | | } |
| | | 59 | | } |
| | | 60 | | |
| | | 61 | | public class ConsoleLogCaptureShellInitializer(ConsoleLogCaptureShellLease lease) : IShellInitializer |
| | | 62 | | { |
| | | 63 | | public Task InitializeAsync(CancellationToken cancellationToken = default) => lease.StartAsync(cancellationToken); |
| | | 64 | | } |
| | | 65 | | |
| | 3 | 66 | | public class ConsoleLogCaptureShellDrainHandler(ConsoleLogCaptureShellLease lease) : IDrainHandler |
| | | 67 | | { |
| | 2 | 68 | | public Task DrainAsync(IDrainExtensionHandle extensionHandle, CancellationToken cancellationToken) => lease.StopAsyn |
| | | 69 | | } |