using System.Buffers; using System.Buffers.Binary; using Google.Protobuf; using ZB.MOM.WW.MxGateway.Contracts.Proto; namespace ZB.MOM.WW.MxGateway.Server.Workers; /// /// Reads length-prefixed WorkerEnvelope protobuf frames from a stream. /// /// /// /// The reader keeps a read-ahead buffer. Each stream read asks /// for as much as the buffer has room for, so one read normally returns a frame's length /// prefix and body together, or several small frames at once. Reading the prefix and the /// body with separate exact-size reads cost two I/O completions per frame, and each /// completion was a thread-pool wake-up (mxaccessgw#235). A frame larger than the buffer is /// assembled in a pooled array: the buffered head is copied in and the rest is read straight /// into it. /// /// /// is not reentrant: the buffer carries bytes from one call to the /// next, so exactly one consumer may be inside a read at a time, and every read of the stream /// must go through this instance. That matches how the reader is used — a single read loop /// per WorkerClient, with handshake reads on the same instance completing before the /// loop starts. /// /// public sealed class WorkerFrameReader { /// /// Size of the read-ahead buffer. Large enough for a burst of typical event frames (a few /// hundred bytes each) in one read, and below the 85,000-byte large-object-heap threshold so /// the per-reader allocation stays in the ordinary heap. /// internal const int ReadBufferBytes = 64 * 1024; private const int LengthPrefixBytes = sizeof(uint); private readonly WorkerFrameProtocolOptions _options; private readonly Stream _stream; // One buffer per reader (one reader per worker pipe), owned for the reader's lifetime. It is // a plain array rather than an ArrayPool rental because the reader has no disposal point to // return a rental from. Bytes [_start, _end) are read but not yet consumed. private readonly byte[] _buffer = new byte[ReadBufferBytes]; private int _start; private int _end; /// /// Initializes a new instance of . /// /// Stream to read frames from. /// Frame protocol options. public WorkerFrameReader( Stream stream, WorkerFrameProtocolOptions options) { _stream = stream ?? throw new ArgumentNullException(nameof(stream)); _options = options ?? throw new ArgumentNullException(nameof(options)); } private int Buffered => _end - _start; /// /// Reads a worker envelope frame from the stream asynchronously. /// /// Cancellation token. /// Parsed worker envelope. public async ValueTask ReadAsync(CancellationToken cancellationToken = default) { await FillAtLeastAsync(LengthPrefixBytes, cancellationToken).ConfigureAwait(false); uint payloadLength = BinaryPrimitives.ReadUInt32LittleEndian(_buffer.AsSpan(_start, LengthPrefixBytes)); if (payloadLength == 0) { throw new WorkerFrameProtocolException( WorkerFrameProtocolErrorCode.MalformedLength, "Worker frame payload length must be greater than zero."); } // Checked before any payload byte is buffered or allocated, exactly as when the prefix // was read on its own: an oversized declaration never drives a large allocation. if (payloadLength > _options.MaxMessageBytes) { throw new WorkerFrameProtocolException( WorkerFrameProtocolErrorCode.MessageTooLarge, $"Worker frame payload length {payloadLength} exceeds the configured maximum of {_options.MaxMessageBytes} bytes."); } _start += LengthPrefixBytes; int length = checked((int)payloadLength); WorkerEnvelope envelope = length <= _buffer.Length ? await ReadBufferedPayloadAsync(length, cancellationToken).ConfigureAwait(false) : await ReadLargePayloadAsync(length, cancellationToken).ConfigureAwait(false); WorkerEnvelopeValidator.Validate(envelope, _options); return envelope; } private static WorkerEnvelope Parse(byte[] payload, int offset, int length) { try { // ParseFrom copies whatever it needs into the parsed message, so the envelope never // aliases the read buffer and the buffer can be reused for the next frame at once. return WorkerEnvelope.Parser.ParseFrom(payload, offset, length); } catch (InvalidProtocolBufferException exception) { throw new WorkerFrameProtocolException( WorkerFrameProtocolErrorCode.InvalidEnvelope, "Worker frame payload is not a valid WorkerEnvelope protobuf message.", exception); } } private static WorkerFrameProtocolException EndOfStream(EndOfStreamException exception) => new( WorkerFrameProtocolErrorCode.EndOfStream, "Worker frame ended before the expected number of bytes were read.", exception); // The payload fits in the read-ahead buffer: buffer the whole of it and parse in place. private async ValueTask ReadBufferedPayloadAsync(int length, CancellationToken cancellationToken) { await FillAtLeastAsync(length, cancellationToken).ConfigureAwait(false); WorkerEnvelope envelope = Parse(_buffer, _start, length); Consume(length); return envelope; } // The payload is larger than the read-ahead buffer. Rent an exact-size-or-larger array from the // shared pool, as the unbuffered reader did, so frames near the cap do not allocate a fresh LOH // buffer each time; move the buffered head into it and read the remainder directly. Reading // the remainder exactly (not ahead) means the read-ahead buffer is empty afterwards. private async ValueTask ReadLargePayloadAsync(int length, CancellationToken cancellationToken) { byte[] payload = ArrayPool.Shared.Rent(length); try { int head = Buffered; Buffer.BlockCopy(_buffer, _start, payload, 0, head); _start = 0; _end = 0; try { await _stream.ReadExactlyAsync(payload.AsMemory(head, length - head), cancellationToken) .ConfigureAwait(false); } catch (EndOfStreamException exception) { throw EndOfStream(exception); } return Parse(payload, 0, length); } finally { ArrayPool.Shared.Return(payload); } } private void Consume(int count) { _start += count; if (_start == _end) { // Empty: rewind so the next read has the whole buffer to fill. _start = 0; _end = 0; } } // Ensures at least `count` unconsumed bytes are buffered (count <= buffer length). Moves the // unconsumed tail to the front first when the frame would not otherwise fit, then reads as much // as the free space allows until enough has arrived. A zero-byte read before that is the end of // the stream, reported as EndOfStream like the exact reads it replaces — including at a frame // boundary, where the stream ending cleanly is still a disconnect to the caller. private async ValueTask FillAtLeastAsync(int count, CancellationToken cancellationToken) { if (Buffered >= count) { return; } if (_start + count > _buffer.Length) { int buffered = Buffered; Buffer.BlockCopy(_buffer, _start, _buffer, 0, buffered); _start = 0; _end = buffered; } while (Buffered < count) { int read = await _stream.ReadAsync(_buffer.AsMemory(_end), cancellationToken).ConfigureAwait(false); if (read == 0) { throw EndOfStream(new EndOfStreamException()); } _end += read; } } }