diff --git a/docs/WorkerFrameProtocol.md b/docs/WorkerFrameProtocol.md index 26363b0d..9b3f7167 100644 --- a/docs/WorkerFrameProtocol.md +++ b/docs/WorkerFrameProtocol.md @@ -22,6 +22,18 @@ public gRPC cap plus a 64 KiB envelope-overhead reserve (16842752 bytes) so a maximally-sized accepted gRPC payload always fits one worker frame once wrapped in a `WorkerEnvelope`. +The gateway's reader (`ZB.MOM.WW.MxGateway.Server.Workers.WorkerFrameReader`) +reads ahead into a 64 KiB buffer rather than issuing an exact read for the +prefix and another for the body. One pipe read then normally yields a whole +frame, or several frames when the worker wrote a batch, instead of two I/O +completions — two thread-pool wake-ups — per frame (mxaccessgw#235). The length +checks still run on the prefix alone, before anything is allocated for the +payload. A frame larger than the buffer is assembled in a pooled array from the +buffered head and an exact read of the rest. The stream ending anywhere inside a +frame, or between frames, is reported as `EndOfStream` as before. Because the +buffer carries bytes between calls, every read of the gateway end of the pipe +goes through the one reader instance, handshake included. + The gateway is the source of truth for this maximum: it conveys the negotiated value in the handshake as `GatewayHello.max_frame_bytes`, and the worker adopts it as its `WorkerFrameProtocolOptions.MaxMessageBytes` instead of a hard-coded diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameReader.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameReader.cs index 70964bc3..b52f3582 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameReader.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameReader.cs @@ -9,19 +9,43 @@ namespace ZB.MOM.WW.MxGateway.Server.Workers; /// Reads length-prefixed WorkerEnvelope protobuf frames from a stream. /// /// -/// is not reentrant: the reader keeps a per-instance length-prefix scratch -/// buffer, so exactly one consumer may be inside a read at a time. That matches how the reader is -/// used — a single read loop per WorkerClient, with handshake reads completing before the -/// loop starts. +/// +/// 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; - // Reused across frames rather than allocated per read. Safe because ReadAsync is - // single-consumer by construction; the prefix is fully overwritten by every read. - private readonly byte[] _lengthPrefix = new byte[sizeof(uint)]; + // 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 . @@ -36,6 +60,8 @@ public sealed class WorkerFrameReader _options = options ?? throw new ArgumentNullException(nameof(options)); } + private int Buffered => _end - _start; + /// /// Reads a worker envelope frame from the stream asynchronously. /// @@ -43,9 +69,9 @@ public sealed class WorkerFrameReader /// Parsed worker envelope. public async ValueTask ReadAsync(CancellationToken cancellationToken = default) { - await ReadExactlyOrThrowAsync(_lengthPrefix, cancellationToken).ConfigureAwait(false); + await FillAtLeastAsync(LengthPrefixBytes, cancellationToken).ConfigureAwait(false); - uint payloadLength = BinaryPrimitives.ReadUInt32LittleEndian(_lengthPrefix); + uint payloadLength = BinaryPrimitives.ReadUInt32LittleEndian(_buffer.AsSpan(_start, LengthPrefixBytes)); if (payloadLength == 0) { throw new WorkerFrameProtocolException( @@ -53,6 +79,8 @@ public sealed class WorkerFrameReader "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( @@ -60,55 +88,122 @@ public sealed class WorkerFrameReader $"Worker frame payload length {payloadLength} exceeds the configured maximum of {_options.MaxMessageBytes} bytes."); } - // Rent the payload buffer from the shared pool rather than allocating a fresh byte[] per - // frame; large event frames near the cap would otherwise allocate an LOH buffer each time. - // ParseFrom copies whatever it needs into the parsed message, so the rented buffer - // can be returned as soon as parsing completes without the envelope aliasing it. The rented - // buffer may be larger than requested, so the read and parse are bounded to length. + _start += LengthPrefixBytes; int length = checked((int)payloadLength); - byte[] payload = ArrayPool.Shared.Rent(length); - WorkerEnvelope envelope; - try - { - await ReadExactlyOrThrowAsync(new Memory(payload, 0, length), cancellationToken) - .ConfigureAwait(false); - try - { - envelope = WorkerEnvelope.Parser.ParseFrom(payload, 0, length); - } - catch (InvalidProtocolBufferException exception) - { - throw new WorkerFrameProtocolException( - WorkerFrameProtocolErrorCode.InvalidEnvelope, - "Worker frame payload is not a valid WorkerEnvelope protobuf message.", - exception); - } - } - finally - { - ArrayPool.Shared.Return(payload); - } + WorkerEnvelope envelope = length <= _buffer.Length + ? await ReadBufferedPayloadAsync(length, cancellationToken).ConfigureAwait(false) + : await ReadLargePayloadAsync(length, cancellationToken).ConfigureAwait(false); WorkerEnvelopeValidator.Validate(envelope, _options); return envelope; } - private async ValueTask ReadExactlyOrThrowAsync( - Memory buffer, - CancellationToken cancellationToken) + private static WorkerEnvelope Parse(byte[] payload, int offset, int length) { try { - await _stream.ReadExactlyAsync(buffer, cancellationToken).ConfigureAwait(false); + // 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 (EndOfStreamException exception) + catch (InvalidProtocolBufferException exception) { throw new WorkerFrameProtocolException( - WorkerFrameProtocolErrorCode.EndOfStream, - "Worker frame ended before the expected number of bytes were read.", + 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; + } + } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs index ecc452b8..ea92ded0 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs @@ -212,6 +212,162 @@ public sealed class WorkerFrameProtocolTests Assert.Equal(WorkerFrameProtocolErrorCode.InvalidEnvelope, exception.ErrorCode); } + /// + /// Several small frames that arrive together are served from one stream read: the reader + /// reads ahead into its buffer instead of issuing an exact read for each length prefix and + /// each body, which cost two I/O completions per frame. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadAsync_WithSeveralFramesInOneRead_ServesThemFromOneStreamRead() + { + WorkerFrameProtocolOptions options = new(SessionId); + List originals = CreateEnvelopes(count: 8, versionLength: index => 20 + index); + await using ChunkedReadStream stream = new(Concat(originals), chunkSize: int.MaxValue); + + WorkerFrameReader reader = new(stream, options); + foreach (WorkerEnvelope original in originals) + { + Assert.Equal(original, await reader.ReadAsync()); + } + + Assert.Equal(1, stream.ReadCallCount); + } + + /// + /// Frames whose prefixes and bodies are split at arbitrary points across reads — including + /// a prefix split in two — reassemble in order. + /// + /// Maximum bytes the stream returns per read. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(1)] + [InlineData(3)] + [InlineData(7)] + [InlineData(61)] + public async Task ReadAsync_WithFramesSplitAcrossReads_ReassemblesEveryFrame(int chunkSize) + { + WorkerFrameProtocolOptions options = new(SessionId); + List originals = CreateEnvelopes(count: 6, versionLength: index => 13 * index); + await using ChunkedReadStream stream = new(Concat(originals), chunkSize); + + WorkerFrameReader reader = new(stream, options); + foreach (WorkerEnvelope original in originals) + { + Assert.Equal(original, await reader.ReadAsync()); + } + } + + /// + /// A frame that straddles the end of the read-ahead buffer is moved to the front and + /// completed, and frames after it still parse: the buffer is reused across frames. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadAsync_WithFramesStraddlingTheReadBufferEnd_ReassemblesEveryFrame() + { + WorkerFrameProtocolOptions options = new(SessionId); + + // Each frame is roughly a third of the buffer, so the third one crosses the buffer end + // whatever the exact envelope overhead is. + List originals = CreateEnvelopes( + count: 7, + versionLength: _ => (WorkerFrameReader.ReadBufferBytes / 3) - 100); + await using ChunkedReadStream stream = new(Concat(originals), chunkSize: int.MaxValue); + + WorkerFrameReader reader = new(stream, options); + foreach (WorkerEnvelope original in originals) + { + Assert.Equal(original, await reader.ReadAsync()); + } + } + + /// + /// A frame larger than the read-ahead buffer is assembled from the buffered head plus a + /// direct read of the rest, and the frames on either side of it still parse. + /// + /// Maximum bytes the stream returns per read. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(int.MaxValue)] + [InlineData(4093)] + public async Task ReadAsync_WithFrameLargerThanReadBuffer_ReassemblesSurroundingFrames(int chunkSize) + { + WorkerFrameProtocolOptions options = new(SessionId, GatewayContractInfo.WorkerProtocolVersion, maxMessageBytes: 1024 * 1024); + List originals = CreateEnvelopes( + count: 3, + versionLength: index => index == 2 ? 3 * WorkerFrameReader.ReadBufferBytes : 50); + await using ChunkedReadStream stream = new(Concat(originals), chunkSize); + + WorkerFrameReader reader = new(stream, options); + foreach (WorkerEnvelope original in originals) + { + Assert.Equal(original, await reader.ReadAsync()); + } + } + + /// + /// The size limit is still enforced from the prefix alone, even when the oversized frame's + /// body bytes arrive in the same read. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadAsync_WithOversizedFrameAndBodyInSameRead_ThrowsMessageTooLarge() + { + WorkerFrameProtocolOptions options = new(SessionId, GatewayContractInfo.WorkerProtocolVersion, maxMessageBytes: 16); + await using MemoryStream stream = new(CreateFrame(new byte[17])); + + WorkerFrameReader reader = new(stream, options); + WorkerFrameProtocolException exception = + await Assert.ThrowsAsync( + async () => await reader.ReadAsync()); + + Assert.Equal(WorkerFrameProtocolErrorCode.MessageTooLarge, exception.ErrorCode); + } + + /// + /// The stream ending anywhere inside a frame — in the prefix, in a buffered body, in a body + /// larger than the read-ahead buffer — or cleanly between frames reports + /// with an + /// inner exception, as the exact reads it replaced did. + /// + /// Where the stream ends. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData("prefix")] + [InlineData("body")] + [InlineData("large-body")] + [InlineData("boundary")] + public async Task ReadAsync_WhenStreamEndsMidFrame_ThrowsEndOfStream(string truncation) + { + WorkerFrameProtocolOptions options = new(SessionId, GatewayContractInfo.WorkerProtocolVersion, maxMessageBytes: 1024 * 1024); + WorkerEnvelope first = CreateEnvelope(); + WorkerEnvelope second = CreateEnvelope(); + second.WorkerHello.WorkerVersion = truncation == "large-body" + ? new string('L', 2 * WorkerFrameReader.ReadBufferBytes) + : "second"; + byte[] firstFrame = CreateFrame(first); + byte[] secondFrame = CreateFrame(second); + int secondBytes = truncation switch + { + "prefix" => 2, + "body" => secondFrame.Length - 1, + "large-body" => secondFrame.Length - 1, + _ => 0, + }; + byte[] data = [.. firstFrame, .. secondFrame.AsSpan(0, secondBytes)]; + await using ChunkedReadStream stream = new(data, chunkSize: 4096); + + WorkerFrameReader reader = new(stream, options); + Assert.Equal(first, await reader.ReadAsync()); + WorkerFrameProtocolException exception = + await Assert.ThrowsAsync( + async () => await reader.ReadAsync()); + + Assert.Equal(WorkerFrameProtocolErrorCode.EndOfStream, exception.ErrorCode); + Assert.IsType(exception.InnerException); + } + /// Verifies that writing an oversized envelope throws a message too large exception. /// A task that represents the asynchronous operation. [Fact] @@ -247,6 +403,23 @@ public sealed class WorkerFrameProtocolTests }; } + private static List CreateEnvelopes(int count, Func versionLength) + { + List envelopes = []; + for (int index = 1; index <= count; index++) + { + WorkerEnvelope envelope = CreateEnvelope(); + envelope.Sequence = (ulong)index; + envelope.WorkerHello.WorkerVersion = new string((char)('a' + (index % 26)), versionLength(index)); + envelopes.Add(envelope); + } + + return envelopes; + } + + private static byte[] Concat(IEnumerable envelopes) + => [.. envelopes.SelectMany(envelope => CreateFrame(envelope))]; + private static byte[] CreateFrame(IMessage message) { return CreateFrame(message.ToByteArray());