using System.Diagnostics; using System.IO; using System.Text; using Azaion.Common.DTO; using MessagePack; using NetMQ; using NetMQ.Sockets; using Serilog; using Exception = System.Exception; namespace Azaion.Common.Services; public class LoaderClient(LoaderClientConfig config, ILogger logger, CancellationToken ct = default) : IDisposable { private readonly DealerSocket _dealer = new(); private readonly Guid _clientId = Guid.NewGuid(); public void StartClient() { try { using var process = new Process(); process.StartInfo = new ProcessStartInfo { FileName = Constants.EXTERNAL_LOADER_PATH, Arguments = $"--port {config.ZeroMqPort} --api {config.ApiUrl}", CreateNoWindow = true }; process.Start(); } catch (Exception e) { logger.Error(e, e.Message); throw; } } public void Connect() { _dealer.Options.Identity = Encoding.UTF8.GetBytes(_clientId.ToString("N")); _dealer.Connect($"tcp://{config.ZeroMqHost}:{config.ZeroMqPort}"); } public void Login(ApiCredentials credentials) { var result = SendCommand(RemoteCommand.Create(CommandType.Login, credentials)); if (result.CommandType != CommandType.Ok) throw new Exception(result.Message); } public MemoryStream LoadFile(string filename, string folder) { var result = SendCommand(RemoteCommand.Create(CommandType.Load, new LoadFileData(filename, folder))); if (result.Data?.Length == 0) throw new Exception($"Can't load {filename}. Returns 0 bytes"); return new MemoryStream(result.Data!); } private RemoteCommand SendCommand(RemoteCommand command, int retryCount = 50, int retryDelayMs = 800) { try { _dealer.SendFrame(MessagePackSerializer.Serialize(command)); var tryNum = 0; while (!ct.IsCancellationRequested && tryNum++ < retryCount) { if (!_dealer.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(retryDelayMs), out var bytes)) continue; var res = MessagePackSerializer.Deserialize(bytes, cancellationToken: ct); if (res.CommandType == CommandType.Error) throw new Exception(res.Message); return res; } throw new Exception($"Sent {command} {retryCount} times, with wait time {retryDelayMs}ms for each call. No response from client."); } catch (Exception e) { logger.Error(e, e.Message); throw; } } public void Stop() { _dealer.SendFrame(MessagePackSerializer.Serialize(new RemoteCommand(CommandType.Exit))); } public void Dispose() { _dealer.Dispose(); } }