diff --git a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs index 216f2aa3..36e0a081 100644 --- a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs +++ b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs @@ -348,6 +348,7 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo internal sealed class FakeTlsStream(Stream inner) : Stream { private readonly byte[] _header = new byte[5]; + private byte[]? _record; private int _recordLeft; public override bool CanRead => true; @@ -380,7 +381,12 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation { if (length > 0) { - await inner.ReadExactlyAsync(new byte[length], cancellationToken).ConfigureAwait(false); + _record ??= new byte[5 + FakeTls.MaxRecordPayload]; + await inner.ReadExactlyAsync(_record.AsMemory(0, Math.Min(length, _record.Length)), cancellationToken).ConfigureAwait(false); + if (length > _record.Length) + { + await inner.ReadExactlyAsync(new byte[length - _record.Length], cancellationToken).ConfigureAwait(false); + } } continue; @@ -404,8 +410,29 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation return n; } - public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => - await inner.WriteAsync(Wrap(buffer.Span), cancellationToken).ConfigureAwait(false); + /// + /// Writes records through one reusable buffer instead of allocating the wrapped payload (issue #359). + /// The bytes on the wire are identical to . + /// + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + _record ??= new byte[5 + FakeTls.MaxRecordPayload]; + for (var offset = 0; offset < buffer.Length; offset += FakeTls.MaxRecordPayload) + { + var length = WriteRecord(buffer.Span.Slice(offset, Math.Min(FakeTls.MaxRecordPayload, buffer.Length - offset)), _record); + await inner.WriteAsync(_record.AsMemory(0, length), cancellationToken).ConfigureAwait(false); + } + } + + private static int WriteRecord(ReadOnlySpan chunk, Span output) + { + output[0] = FakeTls.RecordApplicationData; + output[1] = 0x03; + output[2] = 0x03; + BinaryPrimitives.WriteUInt16BigEndian(output[3..], (ushort)chunk.Length); + chunk.CopyTo(output[5..]); + return 5 + chunk.Length; + } public static byte[] Wrap(ReadOnlySpan data) { diff --git a/src/Bydlo.Engines/TgWsProxy/MtProto.cs b/src/Bydlo.Engines/TgWsProxy/MtProto.cs index 5536991a..4ba8025f 100644 --- a/src/Bydlo.Engines/TgWsProxy/MtProto.cs +++ b/src/Bydlo.Engines/TgWsProxy/MtProto.cs @@ -155,21 +155,31 @@ internal sealed class MsgSplitter(uint protoTag) private int _length; private bool _disabled; - public List Split(ReadOnlySpan cipher, ReadOnlySpan plain) + private int _pending; + + /// + /// Appends a chunk and reports the whole packets now available, without allocating (issue #359): + /// the packets are contiguous in the returned memory and receives + /// their sizes. The memory stays valid only until the next call to this splitter. + /// + public ReadOnlyMemory SplitInto(ReadOnlySpan cipher, ReadOnlySpan plain, List lengths) { - var parts = new List(); + lengths.Clear(); + Consume(_pending); + _pending = 0; if (cipher.IsEmpty) { - return parts; + return ReadOnlyMemory.Empty; } + Append(cipher, plain); if (_disabled) { - parts.Add(cipher.ToArray()); - return parts; + lengths.Add(_length); + _pending = _length; + return _cipher.AsMemory(0, _length); } - Append(cipher, plain); var offset = 0; while (offset < _length) { @@ -182,22 +192,40 @@ public List Split(ReadOnlySpan cipher, ReadOnlySpan plain) if (packet <= 0) { // Unknown framing: stop splitting and pass everything through as is. - parts.Add(_cipher.AsSpan(offset, _length - offset).ToArray()); + lengths.Add(_length - offset); offset = _length; _disabled = true; break; } - parts.Add(_cipher.AsSpan(offset, packet.Value).ToArray()); + lengths.Add(packet.Value); offset += packet.Value; } - Consume(offset); + _pending = offset; + return _cipher.AsMemory(0, offset); + } + + /// Allocating form of , kept for tests and rare paths. + public List Split(ReadOnlySpan cipher, ReadOnlySpan plain) + { + var lengths = new List(); + var packets = SplitInto(cipher, plain, lengths).Span; + var parts = new List(lengths.Count); + var at = 0; + foreach (var length in lengths) + { + parts.Add(packets.Slice(at, length).ToArray()); + at += length; + } + return parts; } public byte[]? Flush() { + Consume(_pending); + _pending = 0; if (_length == 0) { return null; diff --git a/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs b/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs index 9d8f0d18..8189ae50 100644 --- a/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs +++ b/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs @@ -31,6 +31,8 @@ internal sealed class RawWebSocket : IAsyncDisposable private readonly Stream _stream; private readonly SemaphoreSlim _writeLock = new(1, 1); private readonly byte[] _header = new byte[14]; + private readonly int[] _single = new int[1]; + private byte[] _writeBuffer = new byte[16 * 1024]; private readonly Channel _messages = Channel.CreateBounded(new BoundedChannelOptions(16) { SingleReader = true, SingleWriter = true }); private readonly CancellationTokenSource _stopPump = new(); private readonly Task _pump; @@ -77,16 +79,25 @@ internal static async Task UpgradeAsync(Stream stream, string doma await stream.WriteAsync(Encoding.ASCII.GetBytes(request), ct).ConfigureAwait(false); await stream.FlushAsync(ct).ConfigureAwait(false); - var statusLine = await ReadResponseHeadAsync(stream, ct).ConfigureAwait(false); + var (statusLine, rest) = await ReadResponseHeadAsync(stream, ct).ConfigureAwait(false); var parts = statusLine.Split(' ', 3); var status = parts.Length >= 2 && int.TryParse(parts[1], out var code) ? code : 0; - return status == 101 ? new RawWebSocket(stream) : throw new WsHandshakeException(status, statusLine); + if (status != 101) + { + throw new WsHandshakeException(status, statusLine); + } + + return new RawWebSocket(rest.Length == 0 ? stream : new PrefixedStream(rest, stream)); } - public Task SendAsync(ReadOnlyMemory data, CancellationToken ct) => WriteFramesAsync([data], OpBinary, ct); + public Task SendAsync(ReadOnlyMemory data, CancellationToken ct) => WriteFramesAsync(data, null, OpBinary, ct); - public Task SendBatchAsync(IReadOnlyList parts, CancellationToken ct) => - WriteFramesAsync([.. parts.Select(p => (ReadOnlyMemory)p)], OpBinary, ct); + /// + /// Sends contiguous as one binary frame per entry of , + /// built in a reusable buffer and written at once (issue #359). + /// + public Task SendPacketsAsync(ReadOnlyMemory data, IReadOnlyList lengths, CancellationToken ct) => + WriteFramesAsync(data, lengths, OpBinary, ct); /// Next binary message, or null once the server closed the connection. public async Task ReceiveAsync(CancellationToken ct) @@ -109,7 +120,7 @@ public async ValueTask DisposeAsync() try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1)); - await WriteFramesAsync([ReadOnlyMemory.Empty], OpClose, cts.Token, force: true).ConfigureAwait(false); + await WriteFramesAsync(ReadOnlyMemory.Empty, null, OpClose, cts.Token, force: true).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or ObjectDisposedException or OperationCanceledException or NotSupportedException) { } } @@ -134,11 +145,11 @@ private async Task PumpAsync() { case OpClose: Interlocked.Exchange(ref _closed, 1); - try { await WriteFramesAsync([payload.AsMemory(0, Math.Min(2, payload.Length))], OpClose, ct, force: true).ConfigureAwait(false); } + try { await WriteFramesAsync(payload.AsMemory(0, Math.Min(2, payload.Length)), null, OpClose, ct, force: true).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or ObjectDisposedException or OperationCanceledException) { } return; case OpPing: - try { await WriteFramesAsync([payload], OpPong, ct).ConfigureAwait(false); } + try { await WriteFramesAsync(payload, null, OpPong, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or ObjectDisposedException) { } continue; case OpContinuation or OpText or OpBinary: @@ -182,11 +193,20 @@ private async Task PumpAsync() } } + private static int HeaderLength(int length, bool mask) => + 2 + (length < 126 ? 0 : length < 65536 ? 2 : 8) + (mask ? 4 : 0); + internal static byte[] BuildFrame(byte opcode, ReadOnlySpan data, bool mask) + { + var frame = new byte[HeaderLength(data.Length, mask) + data.Length]; + WriteFrame(opcode, data, mask, frame); + return frame; + } + + /// Writes one frame into and returns its length. + private static int WriteFrame(byte opcode, ReadOnlySpan data, bool mask, Span frame) { var length = data.Length; - var headerLength = 2 + (length < 126 ? 0 : length < 65536 ? 2 : 8) + (mask ? 4 : 0); - var frame = new byte[headerLength + length]; frame[0] = (byte)(0x80 | opcode); var maskBit = mask ? (byte)0x80 : (byte)0; var at = 2; @@ -197,28 +217,28 @@ internal static byte[] BuildFrame(byte opcode, ReadOnlySpan data, bool mas else if (length < 65536) { frame[1] = (byte)(maskBit | 126); - BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(2), (ushort)length); + BinaryPrimitives.WriteUInt16BigEndian(frame[2..], (ushort)length); at = 4; } else { frame[1] = (byte)(maskBit | 127); - BinaryPrimitives.WriteUInt64BigEndian(frame.AsSpan(2), (ulong)length); + BinaryPrimitives.WriteUInt64BigEndian(frame[2..], (ulong)length); at = 10; } if (!mask) { - data.CopyTo(frame.AsSpan(at)); - return frame; + data.CopyTo(frame[at..]); + return at + length; } - var key = frame.AsSpan(at, 4); + var key = frame.Slice(at, 4); RandomNumberGenerator.Fill(key); - var payload = frame.AsSpan(at + 4); + var payload = frame.Slice(at + 4, length); data.CopyTo(payload); ApplyMask(payload, key); - return frame; + return at + 4 + length; } private static void ApplyMask(Span payload, ReadOnlySpan key) @@ -229,44 +249,77 @@ private static void ApplyMask(Span payload, ReadOnlySpan key) } } - private static async Task ReadResponseHeadAsync(Stream stream, CancellationToken ct) + /// + /// Reads the HTTP response head in blocks (issue #359). Bytes that arrive after the blank line + /// already belong to the WebSocket and are returned as Leftover. + /// + private static async Task<(string StatusLine, byte[] Leftover)> ReadResponseHeadAsync(Stream stream, CancellationToken ct) { - // Byte by byte so nothing after the header block is consumed. - var head = new List(256); - var one = new byte[1]; - while (head.Count < 16 * 1024) + const int Limit = 16 * 1024; + var head = new byte[Limit]; + var count = 0; + var end = -1; + while (count < Limit) { - if (await stream.ReadAsync(one, ct).ConfigureAwait(false) == 0) + var n = await stream.ReadAsync(head.AsMemory(count), ct).ConfigureAwait(false); + if (n == 0) { break; } - head.Add(one[0]); - var n = head.Count; - if (n >= 4 && head[n - 4] == '\r' && head[n - 3] == '\n' && head[n - 2] == '\r' && head[n - 1] == '\n') + var from = Math.Max(0, count - 3); + count += n; + var found = head.AsSpan(from, count - from).IndexOf("\r\n\r\n"u8); + if (found >= 0) { + end = from + found + 4; break; } } - var text = Encoding.UTF8.GetString([.. head]); + var text = Encoding.UTF8.GetString(head, 0, end >= 0 ? end : count); var firstLine = text.Split('\n', 2)[0].Trim(); - return firstLine.Length == 0 ? throw new WsHandshakeException(0, "empty response") : firstLine; + var rest = end >= 0 && end < count ? head.AsSpan(end, count - end).ToArray() : []; + return firstLine.Length == 0 ? throw new WsHandshakeException(0, "empty response") : (firstLine, rest); } - private async Task WriteFramesAsync(IReadOnlyList> payloads, byte opcode, CancellationToken ct, bool force = false) + private async Task WriteFramesAsync(ReadOnlyMemory data, IReadOnlyList? lengths, byte opcode, CancellationToken ct, bool force = false) { if (IsClosed && !force) { throw new IOException("WebSocket is closed."); } - var frames = payloads.Select(p => BuildFrame(opcode, p.Span, mask: true)).ToArray(); - var buffer = frames.Length == 1 ? frames[0] : [.. frames.SelectMany(f => f)]; await _writeLock.WaitAsync(ct).ConfigureAwait(false); try { - await _stream.WriteAsync(buffer, ct).ConfigureAwait(false); + // The shared buffers are only touched under the write lock. + if (lengths is null) + { + _single[0] = data.Length; + lengths = _single; + } + + var total = 0; + for (var i = 0; i < lengths.Count; i++) + { + total += HeaderLength(lengths[i], mask: true) + lengths[i]; + } + + if (_writeBuffer.Length < total) + { + _writeBuffer = new byte[Math.Max(total, _writeBuffer.Length * 2)]; + } + + var written = 0; + var offset = 0; + for (var i = 0; i < lengths.Count; i++) + { + written += WriteFrame(opcode, data.Span.Slice(offset, lengths[i]), mask: true, _writeBuffer.AsSpan(written)); + offset += lengths[i]; + } + + await _stream.WriteAsync(_writeBuffer.AsMemory(0, written), ct).ConfigureAwait(false); await _stream.FlushAsync(ct).ConfigureAwait(false); } finally @@ -298,7 +351,7 @@ private async Task WriteFramesAsync(IReadOnlyList> payloads throw new IOException($"WebSocket frame too large: {length} bytes."); } - var key = new byte[4]; + var key = _header.AsMemory(10, 4); if (masked) { await _stream.ReadExactlyAsync(key, ct).ConfigureAwait(false); @@ -308,9 +361,75 @@ private async Task WriteFramesAsync(IReadOnlyList> payloads await _stream.ReadExactlyAsync(payload, ct).ConfigureAwait(false); if (masked) { - ApplyMask(payload, key); + ApplyMask(payload, key.Span); } return (opcode, payload, fin); } } + +/// Replays bytes read past the HTTP head before continuing with the inner stream. +internal sealed class PrefixedStream(byte[] prefix, Stream inner) : Stream +{ + private int _offset; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => inner.CanWrite; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_offset < prefix.Length && !buffer.IsEmpty) + { + var n = Math.Min(buffer.Length, prefix.Length - _offset); + prefix.AsSpan(_offset, n).CopyTo(buffer.Span); + _offset += n; + return ValueTask.FromResult(n); + } + + return inner.ReadAsync(buffer, cancellationToken); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + inner.WriteAsync(buffer, cancellationToken); + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + inner.WriteAsync(buffer, offset, count, cancellationToken); + + public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count); + + public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken); + + public override void Flush() => inner.Flush(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override async ValueTask DisposeAsync() + { + await inner.DisposeAsync().ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } +} diff --git a/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs b/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs index f157c670..a136508e 100644 --- a/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs +++ b/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs @@ -380,6 +380,7 @@ async Task ClientToWs() { var buffer = new byte[ReadBufferSize]; var plain = new byte[ReadBufferSize]; + var lengths = new List(); try { while (true) @@ -399,14 +400,11 @@ async Task ClientToWs() up += n; upPackets++; crypto.Upstream(buffer.AsSpan(0, n), plain.AsSpan(0, n)); - var parts = splitter.Split(buffer.AsSpan(0, n), plain.AsSpan(0, n)); - if (parts.Count == 1) + // Packets stay in the splitter's buffer; frames are built in the socket's own buffer (#359). + var packets = splitter.SplitInto(buffer.AsSpan(0, n), plain.AsSpan(0, n), lengths); + if (lengths.Count > 0) { - await ws.SendAsync(parts[0], session.Token).ConfigureAwait(false); - } - else if (parts.Count > 1) - { - await ws.SendBatchAsync(parts, session.Token).ConfigureAwait(false); + await ws.SendPacketsAsync(packets, lengths, session.Token).ConfigureAwait(false); } } } diff --git a/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs b/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs new file mode 100644 index 00000000..8b1e0705 --- /dev/null +++ b/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs @@ -0,0 +1,148 @@ +using System.Buffers.Binary; +using Bydlo.Engines.TgWsProxy; + +namespace Bydlo.Tests; + +/// Allocation-free upstream path (issue #359); wire bytes are unchanged. +public sealed class TgWsProxyAllocationTests +{ + /// Answers the upgrade once (optionally with trailing frame bytes), then idles; writes are recorded or discarded. + private sealed class ScriptedStream(byte[] response, bool record) : Stream + { + private int _offset; + public MemoryStream Written { get; } = new(); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_offset < response.Length) + { + var n = Math.Min(buffer.Length, response.Length - _offset); + response.AsSpan(_offset, n).CopyTo(buffer.Span); + _offset += n; + return n; + } + + await Task.Delay(Timeout.Infinite, cancellationToken); + return 0; + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + if (record) { Written.Write(buffer.Span); } + return ValueTask.CompletedTask; + } + + public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } + + private static readonly byte[] Upgrade = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n"u8.ToArray(); + + private static byte[] Packet(int payload, byte fill) + { + var packet = new byte[4 + payload]; + BinaryPrimitives.WriteUInt32LittleEndian(packet, (uint)payload); + packet.AsSpan(4).Fill(fill); + return packet; + } + + /// Decodes masked client frames back to payloads. + private static List Unframe(ReadOnlySpan wire) + { + var payloads = new List(); + while (!wire.IsEmpty) + { + Assert.Equal(0x82, wire[0]); + Assert.True((wire[1] & 0x80) != 0); + int length = wire[1] & 0x7F, at = 2; + if (length == 126) { length = BinaryPrimitives.ReadUInt16BigEndian(wire[2..]); at = 4; } + else if (length == 127) { length = (int)BinaryPrimitives.ReadUInt64BigEndian(wire[2..]); at = 10; } + var key = wire.Slice(at, 4); + var payload = wire.Slice(at + 4, length).ToArray(); + for (var i = 0; i < payload.Length; i++) { payload[i] ^= key[i & 3]; } + payloads.Add(payload); + wire = wire[(at + 4 + length)..]; + } + + return payloads; + } + + [Fact] + public async Task Frame_bytes_arriving_with_the_upgrade_head_are_not_lost() + { + byte[] frame = [0x82, 0x02, (byte)'x', (byte)'y']; + var stream = new ScriptedStream([.. Upgrade, .. frame], record: false); + await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None); + Assert.Equal("xy"u8.ToArray(), await ws.ReceiveAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10))); + } + + [Fact] + public async Task Packets_go_out_as_one_frame_each_with_the_same_payloads() + { + var stream = new ScriptedStream(Upgrade, record: true); + await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None); + stream.Written.SetLength(0); + var splitter = new MsgSplitter(MtProto.Intermediate); + var lengths = new List(); + byte[][] packets = [Packet(8, 1), Packet(200, 2), Packet(70_000, 3)]; + byte[] chunk = [.. packets.SelectMany(p => p), .. Packet(16, 4).AsSpan(0, 10)]; + var data = splitter.SplitInto(chunk, chunk, lengths); + Assert.Equal(packets.Select(p => p.Length), lengths); + await ws.SendPacketsAsync(data, lengths, CancellationToken.None); + Assert.Equal(packets, Unframe(stream.Written.ToArray())); + + // The partial packet is completed by the next chunk. + var rest = Packet(16, 4)[10..]; + data = splitter.SplitInto(rest, rest, lengths); + Assert.Equal([Packet(16, 4)], [data.ToArray()]); + } + + [Fact] + public async Task Upstream_path_allocates_under_a_fifth_of_a_byte_per_byte() + { + var stream = new ScriptedStream(Upgrade, record: false); + await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None); + var splitter = new MsgSplitter(MtProto.Intermediate); + var lengths = new List(); + // Four packets per 16 KiB read, the last one split across reads. + byte[] stream16 = [.. Packet(4092, 1), .. Packet(4092, 2), .. Packet(4092, 3), .. Packet(4092, 4)]; + var chunk = stream16.AsMemory(0, 16 * 1024 - 100); + var tail = stream16.AsMemory(16 * 1024 - 100); + + async Task Round() + { + var a = splitter.SplitInto(chunk.Span, chunk.Span, lengths); + await ws.SendPacketsAsync(a, lengths, CancellationToken.None); + var b = splitter.SplitInto(tail.Span, tail.Span, lengths); + await ws.SendPacketsAsync(b, lengths, CancellationToken.None); + } + + for (var i = 0; i < 50; i++) { await Round(); } + const int Rounds = 1000; + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < Rounds; i++) { await Round(); } + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + var traffic = (double)Rounds * stream16.Length; + Assert.True(allocated / traffic < 0.2, $"{allocated / traffic:0.000} B per byte"); + } + + [Fact] + public async Task Fake_tls_writes_match_the_reference_wrapping() + { + var sink = new MemoryStream(); + var tls = new FakeTlsStream(sink); + var payload = new byte[40_000]; + Random.Shared.NextBytes(payload); + await tls.WriteAsync(payload.AsMemory()); + Assert.Equal(FakeTlsStream.Wrap(payload), sink.ToArray()); + } +}