|
| 1 | +using System.Diagnostics; |
| 2 | +using ManagedCode.ClaudeCodeSharpSDK.Internal; |
| 3 | + |
| 4 | +namespace ManagedCode.ClaudeCodeSharpSDK.Tests.Unit; |
| 5 | + |
| 6 | +public class BoundedCliProcessProbeTests |
| 7 | +{ |
| 8 | + private const string ShellExecutableUnix = "/bin/sh"; |
| 9 | + private const string ShellExecutableWindows = "cmd.exe"; |
| 10 | + private const string ShellArgumentUnix = "-c"; |
| 11 | + private const string ShellArgumentWindows = "/c"; |
| 12 | + private const string SentinelVariable = "SDK_METADATA_PROBE_SENTINEL"; |
| 13 | + private const string SentinelValue = "explicit-environment-value"; |
| 14 | + private const string OverflowMessage = "CLI metadata process exceeded the configured output limit."; |
| 15 | + private const string TimeoutMessage = "CLI metadata process did not exit within the configured time limit."; |
| 16 | + private const string OutputTimeoutMessage = "CLI metadata process output did not close within the configured time limit."; |
| 17 | + private const string LinuxFixtureSkipReason = "The detached inherited-pipe fixture requires Linux setsid."; |
| 18 | + private const string DetachedChildCommandPrefix = "/usr/bin/setsid /bin/sleep 30 >&2 & echo $! > '"; |
| 19 | + private const string DetachedChildCommandSuffix = "'; exit 0"; |
| 20 | + private const string FixtureDirectoryPrefix = "BoundedCliProcessProbe-"; |
| 21 | + private const string ChildProcessIdFileName = "child.pid"; |
| 22 | + private const string StandardOutputPressureMarker = "stdout-pressure-1999"; |
| 23 | + private const string StandardErrorPressureMarker = "stderr-pressure-1999"; |
| 24 | + private const string StandardInputEofCommandUnix = "cat >/dev/null"; |
| 25 | + private const string StandardInputEofCommandWindows = "more >NUL"; |
| 26 | + private const int DetachedPipeProbeCount = 3; |
| 27 | + private const string SentinelCommandUnix = "printf '%s' \"$SDK_METADATA_PROBE_SENTINEL\""; |
| 28 | + private const string SentinelCommandWindows = "echo %SDK_METADATA_PROBE_SENTINEL%"; |
| 29 | + private const string PressureCommandUnix = |
| 30 | + "i=0; while [ $i -lt 2000 ]; do printf 'stdout-pressure-%s\\n' \"$i\"; printf 'stderr-pressure-%s\\n' \"$i\" >&2; i=$((i+1)); done"; |
| 31 | + private const string PressureCommandWindows = |
| 32 | + "for /L %i in (0,1,1999) do @(echo stdout-pressure-%i&echo stderr-pressure-%i 1>&2)"; |
| 33 | + private const string OverflowCommandUnix = "printf '%01000d' 0"; |
| 34 | + private const string OverflowCommandWindows = "for /L %i in (1,1,200) do @<nul set /p =0123456789"; |
| 35 | + private const string LongRunningCommandUnix = "sleep 20"; |
| 36 | + private const string LongRunningCommandWindows = "ping -n 21 127.0.0.1 >NUL"; |
| 37 | + private static readonly TimeSpan ProbeTimeout = TimeSpan.FromMilliseconds(400); |
| 38 | + private static readonly TimeSpan ProcessTimeout = TimeSpan.FromSeconds(10); |
| 39 | + |
| 40 | + [Test] |
| 41 | + public async Task Run_PreservesExplicitEnvironmentAndCanExcludeParentEnvironment() |
| 42 | + { |
| 43 | + var environment = new Dictionary<string, string>(StringComparer.Ordinal) |
| 44 | + { |
| 45 | + [SentinelVariable] = SentinelValue, |
| 46 | + }; |
| 47 | + |
| 48 | + var result = Run(SentinelCommandUnix, SentinelCommandWindows, environment, inheritEnvironmentVariables: false); |
| 49 | + |
| 50 | + await Assert.That(result.StandardOutput).Contains(SentinelValue); |
| 51 | + } |
| 52 | + |
| 53 | + [Test] |
| 54 | + public async Task Run_InheritsParentEnvironmentWhenRequested() |
| 55 | + { |
| 56 | + var previous = Environment.GetEnvironmentVariable(SentinelVariable); |
| 57 | + Environment.SetEnvironmentVariable(SentinelVariable, SentinelValue); |
| 58 | + try |
| 59 | + { |
| 60 | + var result = Run(SentinelCommandUnix, SentinelCommandWindows, environment: null, inheritEnvironmentVariables: true); |
| 61 | + |
| 62 | + await Assert.That(result.StandardOutput).Contains(SentinelValue); |
| 63 | + } |
| 64 | + finally |
| 65 | + { |
| 66 | + Environment.SetEnvironmentVariable(SentinelVariable, previous); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + [Test] |
| 71 | + public async Task Run_DrainsStandardOutputAndErrorConcurrentlyUnderPressure() |
| 72 | + { |
| 73 | + var result = Run(PressureCommandUnix, PressureCommandWindows, environment: null, |
| 74 | + inheritEnvironmentVariables: true, maximumOutputCharacters: 100000); |
| 75 | + |
| 76 | + await Assert.That(result.ExitCode).IsEqualTo(0); |
| 77 | + await Assert.That(result.StandardOutput).Contains(StandardOutputPressureMarker); |
| 78 | + await Assert.That(result.StandardError).Contains(StandardErrorPressureMarker); |
| 79 | + } |
| 80 | + |
| 81 | + [Test] |
| 82 | + public async Task Run_ClosesStandardInputImmediatelyAfterStart() |
| 83 | + { |
| 84 | + var result = Run(StandardInputEofCommandUnix, StandardInputEofCommandWindows, |
| 85 | + environment: null, inheritEnvironmentVariables: true, timeout: ProbeTimeout); |
| 86 | + |
| 87 | + await Assert.That(result.ExitCode).IsEqualTo(0); |
| 88 | + } |
| 89 | + |
| 90 | + [Test] |
| 91 | + public async Task Run_FailsExplicitlyWhenOutputExceedsConfiguredLimit() |
| 92 | + { |
| 93 | + var exception = await Assert.That(() => Run(OverflowCommandUnix, OverflowCommandWindows, |
| 94 | + environment: null, inheritEnvironmentVariables: true, maximumOutputCharacters: 64)).ThrowsException(); |
| 95 | + |
| 96 | + await Assert.That(exception).IsTypeOf<InvalidOperationException>(); |
| 97 | + await Assert.That(exception!.Message).IsEqualTo(OverflowMessage); |
| 98 | + } |
| 99 | + |
| 100 | + [Test] |
| 101 | + public async Task Run_StopsProcessWhenProbeTimesOut() |
| 102 | + { |
| 103 | + var stopwatch = Stopwatch.StartNew(); |
| 104 | + var exception = await Assert.That(() => Run(LongRunningCommandUnix, LongRunningCommandWindows, |
| 105 | + environment: null, inheritEnvironmentVariables: true, timeout: ProbeTimeout)).ThrowsException(); |
| 106 | + stopwatch.Stop(); |
| 107 | + |
| 108 | + await Assert.That(exception).IsTypeOf<TimeoutException>(); |
| 109 | + await Assert.That(exception!.Message).IsEqualTo(TimeoutMessage); |
| 110 | + await Assert.That(stopwatch.Elapsed).IsLessThan(ProcessTimeout); |
| 111 | + } |
| 112 | + |
| 113 | + [Test] |
| 114 | + public async Task Run_FailsWithinBoundWhenExitedRootHasDescendantHoldingPipes() |
| 115 | + { |
| 116 | + if (!OperatingSystem.IsLinux()) |
| 117 | + { |
| 118 | + Skip.Test(LinuxFixtureSkipReason); |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + var sandbox = Path.Combine(Environment.CurrentDirectory, "tests", ".sandbox", |
| 123 | + $"{FixtureDirectoryPrefix}{Guid.NewGuid():N}"); |
| 124 | + Directory.CreateDirectory(sandbox); |
| 125 | + var childProcessIdPath = Path.Combine(sandbox, ChildProcessIdFileName); |
| 126 | + var detachedCommand = string.Concat(DetachedChildCommandPrefix, childProcessIdPath, |
| 127 | + DetachedChildCommandSuffix); |
| 128 | + try |
| 129 | + { |
| 130 | + for (var attempt = 0; attempt < DetachedPipeProbeCount; attempt++) |
| 131 | + { |
| 132 | + var activeReaders = 0; |
| 133 | + var stopwatch = Stopwatch.StartNew(); |
| 134 | + var exception = await Assert.That(() => BoundedCliProcessProbe.Run( |
| 135 | + ShellExecutableUnix, |
| 136 | + [ShellArgumentUnix, detachedCommand], |
| 137 | + environment: null, |
| 138 | + inheritEnvironmentVariables: true, |
| 139 | + timeout: ProbeTimeout, |
| 140 | + maximumOutputCharacters: 64, |
| 141 | + readerCountChanged: delta => Interlocked.Add(ref activeReaders, delta))).ThrowsException(); |
| 142 | + stopwatch.Stop(); |
| 143 | + |
| 144 | + await Assert.That(exception).IsTypeOf<TimeoutException>(); |
| 145 | + await Assert.That(exception!.Message).IsEqualTo(OutputTimeoutMessage); |
| 146 | + await Assert.That(stopwatch.Elapsed).IsLessThan(ProcessTimeout); |
| 147 | + await Assert.That(activeReaders).IsEqualTo(0); |
| 148 | + } |
| 149 | + } |
| 150 | + finally |
| 151 | + { |
| 152 | + if (File.Exists(childProcessIdPath)) |
| 153 | + { |
| 154 | + var processIdText = File.ReadAllText(childProcessIdPath); |
| 155 | + if (int.TryParse(processIdText, out var processId)) |
| 156 | + { |
| 157 | + using var child = Process.GetProcessById(processId); |
| 158 | + if (!child.HasExited) |
| 159 | + { |
| 160 | + child.Kill(entireProcessTree: true); |
| 161 | + } |
| 162 | + |
| 163 | + child.WaitForExit(1000); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + Directory.Delete(sandbox, recursive: true); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + private static CliProcessProbeResult Run( |
| 172 | + string unixCommand, |
| 173 | + string windowsCommand, |
| 174 | + IReadOnlyDictionary<string, string>? environment, |
| 175 | + bool inheritEnvironmentVariables, |
| 176 | + TimeSpan? timeout = null, |
| 177 | + int maximumOutputCharacters = 200000) |
| 178 | + { |
| 179 | + var executablePath = OperatingSystem.IsWindows() |
| 180 | + ? Path.Combine(Environment.SystemDirectory, ShellExecutableWindows) |
| 181 | + : ShellExecutableUnix; |
| 182 | + var arguments = new[] |
| 183 | + { |
| 184 | + OperatingSystem.IsWindows() ? ShellArgumentWindows : ShellArgumentUnix, |
| 185 | + OperatingSystem.IsWindows() ? windowsCommand : unixCommand, |
| 186 | + }; |
| 187 | + return BoundedCliProcessProbe.Run(executablePath, arguments, environment, inheritEnvironmentVariables, |
| 188 | + timeout ?? ProcessTimeout, maximumOutputCharacters); |
| 189 | + } |
| 190 | +} |
0 commit comments