perf(worker): pooled frame buffers — brings the net48 codec up to the gateway side's GWC-30 pattern

This commit is contained in:
Joseph Doherty
2026-08-15 13:28:29 -04:00
parent 13df92fbd8
commit f56798aeb9
2 changed files with 31 additions and 11 deletions
@@ -9,11 +9,21 @@ using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Worker.Ipc;
/// <summary>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>WorkerPipeSession</c>, with the startup handshake read
/// completing before the loop starts.
/// </remarks>
public sealed class WorkerFrameReader
{
private readonly WorkerFrameProtocolOptions _options;
private readonly Stream _stream;
// Reused across frames rather than allocated per read (GWC-30). Safe because ReadAsync is
// single-consumer by construction; the prefix is fully overwritten by every read.
private readonly byte[] _lengthPrefix = new byte[sizeof(uint)];
/// <summary>Initializes the reader with a stream and protocol options.</summary>
/// <param name="stream">Stream to read frames from.</param>
/// <param name="options">Protocol options for frame validation.</param>
@@ -30,10 +40,9 @@ public sealed class WorkerFrameReader
/// <returns>The validated <see cref="WorkerEnvelope"/> read from the stream.</returns>
public async Task<WorkerEnvelope> ReadAsync(CancellationToken cancellationToken = default)
{
byte[] lengthPrefix = new byte[sizeof(uint)];
await ReadExactlyOrThrowAsync(lengthPrefix, lengthPrefix.Length, cancellationToken).ConfigureAwait(false);
await ReadExactlyOrThrowAsync(_lengthPrefix, sizeof(uint), cancellationToken).ConfigureAwait(false);
uint payloadLength = ReadUInt32LittleEndian(lengthPrefix);
uint payloadLength = ReadUInt32LittleEndian(_lengthPrefix);
if (payloadLength == 0)
{
throw new WorkerFrameProtocolException(