using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; public class JustifiedWorkerEngine { private readonly string _binaryPath; private readonly string _licenseKey; private static readonly SemaphoreSlim _asyncPipeLock = new SemaphoreSlim(1, 1); public JustifiedWorkerEngine(string binaryPath, string licenseKey) { _binaryPath = binaryPath; _licenseKey = licenseKey; } public async Task ExecuteTransformationAsync(string inputJsonPayload) { await _asyncPipeLock.WaitAsync(); try { string singleLinePayload = inputJsonPayload.Replace("\r", "").Replace("\n", "\\n"); var startInfo = new ProcessStartInfo { FileName = _binaryPath, Arguments = $"--pipe --license {_licenseKey}", RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, StandardOutputEncoding = Encoding.UTF8 }; using var process = new Process { StartInfo = startInfo }; process.Start(); using (var writer = process.StandardInput) { await writer.WriteLineAsync(singleLinePayload); } string resultJson = await process.StandardOutput.ReadLineAsync(); await process.WaitForExitAsync(); try { if (resultJson != null && resultJson.Contains("[DATA_INSUFFICIENT_HALT]")) { throw new InvalidOperationException($"Diagnostic Halt: {resultJson}"); } return resultJson; } catch (Exception ex) { Console.WriteLine($"[DIAGNOSTIC INTERCEPT] Client UI preserved. {ex.Message}"); return null; } } finally { _asyncPipeLock.Release(); } } }