using System.IO; using System.Runtime.Serialization.Json; using System.Threading; using System.Threading.Tasks; namespace PlotDirector.Companion.Protocol; public static class FrameCodec { public static async Task WriteAsync(Stream stream, Message message, CancellationToken cancellation) { byte[] payload; using (var buffer = new MemoryStream()) { new DataContractJsonSerializer(typeof(Message)).WriteObject(buffer, message); if (buffer.Length > ProtocolVersion.MaxFrameBytes) throw new InvalidDataException("IPC frame too large."); payload = buffer.ToArray(); } var length = payload.Length; var header = new[] { (byte)length, (byte)(length >> 8), (byte)(length >> 16), (byte)(length >> 24) }; await stream.WriteAsync(header, 0, 4, cancellation).ConfigureAwait(false); await stream.WriteAsync(payload, 0, payload.Length, cancellation).ConfigureAwait(false); await stream.FlushAsync(cancellation).ConfigureAwait(false); } public static async Task ReadAsync(Stream stream, CancellationToken cancellation) { var header = new byte[4]; await ReadExactlyAsync(stream, header, cancellation).ConfigureAwait(false); var length = header[0] | header[1] << 8 | header[2] << 16 | header[3] << 24; if (length <= 0 || length > ProtocolVersion.MaxFrameBytes) throw new InvalidDataException("Invalid IPC frame length."); var payload = new byte[length]; await ReadExactlyAsync(stream, payload, cancellation).ConfigureAwait(false); using (var buffer = new MemoryStream(payload, false)) { var message = (Message?)new DataContractJsonSerializer(typeof(Message)).ReadObject(buffer) ?? throw new InvalidDataException("Empty IPC message."); if (message.CorrelationId == Guid.Empty) throw new InvalidDataException("Missing correlation ID."); return message; } } private static async Task ReadExactlyAsync(Stream stream, byte[] bytes, CancellationToken cancellation) { var offset = 0; while (offset < bytes.Length) { var count = await stream.ReadAsync(bytes, offset, bytes.Length - offset, cancellation).ConfigureAwait(false); if (count == 0) throw new EndOfStreamException("IPC peer disconnected."); offset += count; } } }