using System.Diagnostics; using System.Reflection; using System.Text.Json; namespace UCVL.VPNPlus; internal static class ClientShutdownChildSelfTest { internal static int Run() { var checks = new Dictionary(); var children = new List(); string? error = null; Process Start(int delay, int exitCode) { var info = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false, CreateNoWindow = true }; if (Path.GetFileNameWithoutExtension(Environment.ProcessPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) info.ArgumentList.Add(Assembly.GetExecutingAssembly().Location); info.ArgumentList.Add("--client-shutdown-test-child"); info.ArgumentList.Add(delay.ToString()); info.ArgumentList.Add(exitCode.ToString()); var child = Process.Start(info)!; _ = child.Handle; // Pin the exact owned child before waiting. children.Add(child); return child; } try { var delayed = Start(1200, 0); checks["exact_owned_child_exits_cleanly_before_handoff"] = ClientShutdownScope.WaitForExit([delayed]) && delayed.HasExited; var failed = Start(10, 7); checks["nonzero_old_client_exit_blocks_replacement"] = !ClientShutdownScope.WaitForExit([failed]); var slow = Start(1200, 0); var timer = Stopwatch.StartNew(); checks["timeout_blocks_replacement_without_killing_client"] = !ClientShutdownScope.WaitForExit([slow], TimeSpan.FromMilliseconds(70)) && !slow.HasExited; checks["wait_is_bounded"] = timer.ElapsedMilliseconds < 1000; checks["timed_out_child_can_finish_gracefully"] = ClientShutdownScope.WaitForExit([slow]); checks["all_exact_handles_reap_successfully"] = children.All(c => c.HasExited); } catch (Exception exception) { error = exception.ToString(); } finally { foreach (var child in children) { try { if (!child.HasExited) { child.Kill(entireProcessTree: true); child.WaitForExit(2000); } } catch { } child.Dispose(); } } var passed = error is null && checks.Values.All(v => v); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "client-exit-child-handoff-self-test.json"), JsonSerializer.Serialize(new { Passed = passed, Checks = checks, Error = error, ProductionProcessQueried = false, NetworkingModified = false }, new JsonSerializerOptions { WriteIndented = true })); return passed ? 0 : 87; } }