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.
This commit is contained in:
@@ -9,19 +9,43 @@ namespace ZB.MOM.WW.MxGateway.Server.Workers;
|
||||
/// Reads length-prefixed WorkerEnvelope protobuf frames from a stream.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="ReadAsync"/> 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 <c>WorkerClient</c>, with handshake reads completing before the
|
||||
/// loop starts.
|
||||
/// <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;
|
||||
|
||||
// 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;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="WorkerFrameReader"/>.
|
||||
@@ -36,6 +60,8 @@ public sealed class WorkerFrameReader
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
}
|
||||
|
||||
private int Buffered => _end - _start;
|
||||
|
||||
/// <summary>
|
||||
/// Reads a worker envelope frame from the stream asynchronously.
|
||||
/// </summary>
|
||||
@@ -43,9 +69,9 @@ public sealed class WorkerFrameReader
|
||||
/// <returns>Parsed worker envelope.</returns>
|
||||
public async ValueTask<WorkerEnvelope> 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<byte>.Shared.Rent(length);
|
||||
WorkerEnvelope envelope;
|
||||
try
|
||||
{
|
||||
await ReadExactlyOrThrowAsync(new Memory<byte>(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<byte>.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<byte> 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<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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,6 +212,162 @@ public sealed class WorkerFrameProtocolTests
|
||||
Assert.Equal(WorkerFrameProtocolErrorCode.InvalidEnvelope, exception.ErrorCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ReadAsync_WithSeveralFramesInOneRead_ServesThemFromOneStreamRead()
|
||||
{
|
||||
WorkerFrameProtocolOptions options = new(SessionId);
|
||||
List<WorkerEnvelope> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frames whose prefixes and bodies are split at arbitrary points across reads — including
|
||||
/// a prefix split in two — reassemble in order.
|
||||
/// </summary>
|
||||
/// <param name="chunkSize">Maximum bytes the stream returns per read.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(3)]
|
||||
[InlineData(7)]
|
||||
[InlineData(61)]
|
||||
public async Task ReadAsync_WithFramesSplitAcrossReads_ReassemblesEveryFrame(int chunkSize)
|
||||
{
|
||||
WorkerFrameProtocolOptions options = new(SessionId);
|
||||
List<WorkerEnvelope> 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());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<WorkerEnvelope> 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());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="chunkSize">Maximum bytes the stream returns per read.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(int.MaxValue)]
|
||||
[InlineData(4093)]
|
||||
public async Task ReadAsync_WithFrameLargerThanReadBuffer_ReassemblesSurroundingFrames(int chunkSize)
|
||||
{
|
||||
WorkerFrameProtocolOptions options = new(SessionId, GatewayContractInfo.WorkerProtocolVersion, maxMessageBytes: 1024 * 1024);
|
||||
List<WorkerEnvelope> 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());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The size limit is still enforced from the prefix alone, even when the oversized frame's
|
||||
/// body bytes arrive in the same read.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<WorkerFrameProtocolException>(
|
||||
async () => await reader.ReadAsync());
|
||||
|
||||
Assert.Equal(WorkerFrameProtocolErrorCode.MessageTooLarge, exception.ErrorCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="WorkerFrameProtocolErrorCode.EndOfStream"/> with an
|
||||
/// <see cref="EndOfStreamException"/> inner exception, as the exact reads it replaced did.
|
||||
/// </summary>
|
||||
/// <param name="truncation">Where the stream ends.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<WorkerFrameProtocolException>(
|
||||
async () => await reader.ReadAsync());
|
||||
|
||||
Assert.Equal(WorkerFrameProtocolErrorCode.EndOfStream, exception.ErrorCode);
|
||||
Assert.IsType<EndOfStreamException>(exception.InnerException);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that writing an oversized envelope throws a message too large exception.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -247,6 +403,23 @@ public sealed class WorkerFrameProtocolTests
|
||||
};
|
||||
}
|
||||
|
||||
private static List<WorkerEnvelope> CreateEnvelopes(int count, Func<int, int> versionLength)
|
||||
{
|
||||
List<WorkerEnvelope> 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<WorkerEnvelope> envelopes)
|
||||
=> [.. envelopes.SelectMany(envelope => CreateFrame(envelope))];
|
||||
|
||||
private static byte[] CreateFrame(IMessage message)
|
||||
{
|
||||
return CreateFrame(message.ToByteArray());
|
||||
|
||||
Reference in New Issue
Block a user