fix(GWC-30): reuse the frame reader's length-prefix scratch buffer
ReadAsync allocated a fresh 4-byte array per inbound frame; the GWC-08 pass pooled the payload buffer but left the prefix. Replaced with a per-instance scratch field — the reader is single-consumer by construction (one read loop per WorkerClient, handshake reads complete before the loop starts), so a per-instance buffer is safe and the non-reentrancy that makes it safe is now stated on the class. Pooling four bytes via ArrayPool would cost more than the allocation it saves. Tests: WorkerFrameProtocolTests.ReadAsync_WithMultipleFramesOnOneReader_ ParsesEveryFrame reads five frames of differing payload length through one reader, so a stale prefix carried between calls would misparse.
This commit is contained in:
@@ -5,11 +5,24 @@ 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>
|
||||
/// <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.
|
||||
/// </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 a new instance of <see cref="WorkerFrameReader"/>.
|
||||
/// </summary>
|
||||
@@ -30,10 +43,9 @@ public sealed class WorkerFrameReader
|
||||
/// <returns>Parsed worker envelope.</returns>
|
||||
public async ValueTask<WorkerEnvelope> ReadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
byte[] lengthPrefix = new byte[sizeof(uint)];
|
||||
await ReadExactlyOrThrowAsync(lengthPrefix, cancellationToken).ConfigureAwait(false);
|
||||
await ReadExactlyOrThrowAsync(_lengthPrefix, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
uint payloadLength = BinaryPrimitives.ReadUInt32LittleEndian(lengthPrefix);
|
||||
uint payloadLength = BinaryPrimitives.ReadUInt32LittleEndian(_lengthPrefix);
|
||||
if (payloadLength == 0)
|
||||
{
|
||||
throw new WorkerFrameProtocolException(
|
||||
|
||||
Reference in New Issue
Block a user