Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameReader.cs
T
Joseph Doherty 027d2b5d1a perf(gateway): read worker frames through a 64 KiB read-ahead buffer (#235)
The gateway read each frame with two exact reads, one for the 4-byte prefix and
one for the body, so every frame cost two pipe I/O completions and two
thread-pool wake-ups. WorkerFrameReader now reads as much as its buffer has
room for, so one read normally serves a whole frame or a batch of frames.

Length checks still run on the prefix before any payload allocation; frames
larger than the buffer are assembled in a pooled array; EOF anywhere reports
EndOfStream with an EndOfStreamException inner exception as before. New tests
cover multiple frames per read, frames split across reads, frames straddling
the buffer end, frames larger than the buffer, oversize frames with their body
buffered, and EOF in the prefix, body, large body and at a frame boundary.
2026-12-03 09:36:30 -05:00

210 lines
8.4 KiB
C#

using System.Buffers;
using System.Buffers.Binary;
using Google.Protobuf;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Server.Workers;
/// <summary>
/// Reads length-prefixed WorkerEnvelope protobuf frames from a stream.
/// </summary>
/// <remarks>
/// <para>
/// The reader keeps a <see cref="ReadBufferBytes"/> 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.
/// </para>
/// <para>
/// <see cref="ReadAsync"/> 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 <c>WorkerClient</c>, with handshake reads on the same instance completing before the
/// loop starts.
/// </para>
/// </remarks>
public sealed class WorkerFrameReader
{
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// Initializes a new instance of <see cref="WorkerFrameReader"/>.
/// </summary>
/// <param name="stream">Stream to read frames from.</param>
/// <param name="options">Frame protocol options.</param>
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;
/// <summary>
/// Reads a worker envelope frame from the stream asynchronously.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Parsed worker envelope.</returns>
public async ValueTask<WorkerEnvelope> 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<WorkerEnvelope> 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<WorkerEnvelope> ReadLargePayloadAsync(int length, CancellationToken cancellationToken)
{
byte[] payload = ArrayPool<byte>.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<byte>.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;
}
}
}