using PipeMethodCalls; using PipeShared; using System.Diagnostics; namespace PipeClient; /// /// Owns the server process and the pipe client connected to it. /// internal sealed class ServerConnection(string pipeName, Action log) : IDisposable { private Process? _process; private PipeClient? _client; private string PipeName { get; } = pipeName; public PipeClient Client => _client ?? throw new InvalidOperationException("Not connected to server."); public async Task StartAsync() { var process = StartServerProcess(PipeName); process.EnableRaisingEvents = true; process.Exited += (_, _) => { if (process.ExitCode != 0) log($"Server process exited abnormally (exit code {process.ExitCode})."); }; _process = process; _client = new PipeClient(new JsonFieldsPipeSerializer(), PipeName); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await _client.ConnectAsync(cts.Token); } /// /// Kills the (unresponsive) server process and starts a new one. /// public async Task KillAndRestartAsync() { if (_process is not null) { _process.Kill(entireProcessTree: true); await _process.WaitForExitAsync(); _process.Dispose(); _process = null; } _client?.Dispose(); _client = null; await StartAsync(); } /// /// Waits up to for the server process to exit. /// public bool WaitForServerExit(int milliseconds, out int exitCode) { exitCode = 0; if (_process is null || !_process.WaitForExit(milliseconds)) return false; exitCode = _process.ExitCode; return true; } public void Dispose() { // Disposing the client closes the pipe, the server then exits. _client?.Dispose(); _client = null; if (_process is null) return; if (!_process.WaitForExit(5000)) _process.Kill(); _process.Dispose(); _process = null; } // Start server process (Server is referenced, so its output is copied next to the client). private static Process StartServerProcess(string pipeName) { var baseDir = AppContext.BaseDirectory; var serverExe = Path.Combine(baseDir, OperatingSystem.IsWindows() ? "PipeServer.exe" : "PipeServer"); ProcessStartInfo startInfo; if (File.Exists(serverExe)) { startInfo = new ProcessStartInfo(serverExe); } else { startInfo = new ProcessStartInfo("dotnet"); startInfo.ArgumentList.Add(Path.Combine(baseDir, "PipeServer.dll")); } startInfo.ArgumentList.Add($"{PipeConstants.PipeNameArgPrefix}{pipeName}"); startInfo.UseShellExecute = false; return Process.Start(startInfo) ?? throw new InvalidOperationException("Server could not be started."); } }