using System.Diagnostics; using System.Globalization; using System.Text.Json; using ImageMagick; using Messenger.Api.Services; namespace Messenger.Api.Jobs; internal static class ImageRenderer { public static async Task RenderAsync(Stream input, string mime, long maxPixels, int version, CancellationToken ct) { // Нативное декодирование выполняется в дочернем процессе, который можно завершить по дедлайну. var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { RedirectStandardInput = true, RedirectStandardOutput = true, UseShellExecute = false }; start.ArgumentList.Add(typeof(ImageRenderer).Assembly.Location); start.ArgumentList.Add("--render-attachment"); start.ArgumentList.Add(mime); start.ArgumentList.Add(maxPixels.ToString(CultureInfo.InvariantCulture)); start.ArgumentList.Add(version.ToString(CultureInfo.InvariantCulture)); using var process = Process.Start(start) ?? throw new IOException("Cannot start image renderer"); try { var response = process.StandardOutput.ReadToEndAsync(ct); input.Position = 0; try { await input.CopyToAsync(process.StandardInput.BaseStream, ct); process.StandardInput.Close(); } catch (IOException) { // Дочерний процесс может завершиться до окончания передачи. process.StandardInput.Close(); } await process.WaitForExitAsync(ct); var json = await response; return process.ExitCode switch { 0 => JsonSerializer.Deserialize(json) ?? throw new IOException("Empty renderer result"), 2 => throw new InvalidDataException("Invalid image"), _ => throw new IOException($"Image renderer exit code {process.ExitCode}") }; } finally { if (!process.HasExited) { try { process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } await process.WaitForExitAsync(); } } } public static async Task RunAsync(string mime, long maxPixels, int version) { try { using var original = new LimitedDownloadStream(10485760); await Console.OpenStandardInput().CopyToAsync(original); var result = ImageVariant.CreateAll(original, mime, maxPixels, version); await JsonSerializer.SerializeAsync(Console.OpenStandardOutput(), result); return 0; } catch (Exception ex) when (ex is InvalidDataException or MagickCorruptImageErrorException or MagickCoderErrorException) { return 2; } catch (Exception ex) { Console.Error.WriteLine($"Image renderer: {ex.GetType().Name}"); return 3; } } }