diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs index ba99d29394..89c4743727 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/LengthPrefixCommunicationChannel.cs @@ -18,10 +18,14 @@ namespace Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; /// public class LengthPrefixCommunicationChannel : ICommunicationChannel { + private readonly Stream _stream; + private readonly BinaryReader _reader; private readonly BinaryWriter _writer; + private Exception? _sendFailure; + /// /// Sync object for sending messages /// Write for binarywriter is NOT thread-safe @@ -30,6 +34,7 @@ public class LengthPrefixCommunicationChannel : ICommunicationChannel public LengthPrefixCommunicationChannel(Stream stream) { + _stream = stream; _reader = new BinaryReader(stream, Encoding.UTF8, true); // Using the Buffered stream while writing, improves the write performance. By reducing the number of writes. @@ -42,32 +47,74 @@ public LengthPrefixCommunicationChannel(Stream stream) /// public Task Send(string data) { - try + // Writing Message on binarywriter is not Thread-Safe + // Need to sync one by one to avoid buffer corruption + lock (_writeSyncObject) { - // Writing Message on binarywriter is not Thread-Safe - // Need to sync one by one to avoid buffer corruption - lock (_writeSyncObject) + if (_sendFailure is not null) + { + throw new CommunicationException("Unable to send data over channel because a previous send failed.", _sendFailure); + } + + try { _writer.Write(data); _writer.Flush(); } + catch (NotSupportedException ex) when (!_stream.CanWrite) + { + // As we are simply creating streams around some stream passed as ctor argument, we + // end up in some unsynchronized behavior where it's possible that the outside stream + // was disposed and we are still trying to write something. In such case we would fail + // with "System.NotSupportedException: Stream does not support writing.". + // To avoid being too generic in that catch, I am checking if the stream is not writable. + EqtTrace.Verbose("LengthPrefixCommunicationChannel.Send: Stream is not writable (most likely it was disposed). {0}", ex); + } + catch (Exception ex) + { + FaultChannel(ex); + throw new CommunicationException("Unable to send data over channel.", ex); + } } - catch (NotSupportedException ex) when (!_writer.BaseStream.CanWrite) + + return Task.CompletedTask; + } + + /// + /// Marks the channel unusable after a failed write, and closes the transport. + /// + /// + /// + /// does not report how many bytes it wrote, so once it + /// throws we cannot know whether the length prefix reached the peer without its payload. If it + /// did, the peer is waiting for a body that will never arrive, and every later message would be + /// consumed as part of that frame. + /// + /// + /// There is no way to tell the peer in band, because the framing it is reading is the thing that + /// broke. Closing the transport is the only signal left: the peer reads end of stream, which it + /// already handles. + /// + /// + /// Both callers, SocketClient and SocketServer, build this channel over a TcpClient stream and + /// close that client in their own error paths, so this closes a stream that was already on its + /// way down. Dispose still leaves the stream open, which DisposeShouldNotCloseTheStream pins. + /// + /// + private void FaultChannel(Exception ex) + { + _sendFailure = ex; + + try { - // As we are simply creating streams around some stream passed as ctor argument, we - // end up in some unsynchronized behavior where it's possible that the outside stream - // was disposed and we are still trying to write something. In such case we would fail - // with "System.NotSupportedException: Stream does not support writing.". - // To avoid being too generic in that catch, I am checking if the stream is not writable. - EqtTrace.Verbose("LengthPrefixCommunicationChannel.Send: BaseStream is not writable (most likely it was dispose). {0}", ex); + _stream.Dispose(); } - catch (Exception ex) + catch (Exception disposeException) { - EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); - throw new CommunicationException("Unable to send data over channel.", ex); + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error closing stream after send failure: {0}.", disposeException); } - return Task.CompletedTask; + EqtTrace.Error("LengthPrefixCommunicationChannel.Send: Error sending data: {0}.", ex); } /// @@ -107,16 +154,37 @@ public Task NotifyDataAvailable(CancellationToken cancellationToken) /// public void Dispose() { + // Dispose can run while another thread is inside Send. Take the write lock when it is + // free, so disposal never flushes the writer mid-frame, but never wait for it: blocking + // here would turn a stuck socket write into a shutdown hang. + var lockTaken = false; try { + Monitor.TryEnter(_writeSyncObject, ref lockTaken); + EqtTrace.Verbose("LengthPrefixCommunicationChannel.Dispose: Dispose reader and writer."); _reader.Dispose(); - _writer.Dispose(); + + // BinaryWriter.Dispose flushes its BufferedStream. Skip that flush after a failed + // send, where the buffer can still hold part of an incomplete frame that must not + // reach the peer, and skip it while a send holds the lock, to avoid racing that + // writer. Neither skip loses data: Send flushes after every message it completes. + if (lockTaken && _sendFailure is null) + { + _writer.Dispose(); + } } catch (ObjectDisposedException) { // We don't own the underlying stream lifecycle so it's possible that it's already disposed. } + finally + { + if (lockTaken) + { + Monitor.Exit(_writeSyncObject); + } + } GC.SuppressFinalize(this); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs index 92d65f9115..5ff0630a70 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/LengthPrefixCommunicationChannelTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -25,6 +26,8 @@ public class LengthPrefixCommunicationChannelTests : IDisposable private readonly BinaryWriter _writer; + public TestContext TestContext { get; set; } = null!; + public LengthPrefixCommunicationChannelTests() { _stream = new MemoryStream(); @@ -120,6 +123,31 @@ public void DisposeShouldNotCloseTheStream() Assert.IsTrue(_stream.CanWrite); } + /// + /// Characterization test: it passes on main unchanged, and it passes here. It asserts no new + /// behavior and claims no documented guarantee. Two implementation details combine to let a + /// send after Dispose still reach the stream. BinaryWriter does not track its own disposal, so + /// Write has nothing to reject, and the writer holds the stream with leaveOpen, so disposing + /// the writer flushes rather than closing the stream underneath it. Shutdown leans on the + /// resulting tolerance, because Dispose runs while timer driven sends are still in flight. + /// Pinning it here means a future change surfaces as a failing test rather than as a silent + /// change to shutdown. + /// + [TestMethod] + public async Task SendAfterDisposeShouldStillWriteToTheStream() + { + using var stream = new MemoryStream(); + var channel = new LengthPrefixCommunicationChannel(stream); + channel.Dispose(); + + await channel.Send(Dummydata); + + Assert.IsTrue(stream.CanWrite); + SeekToBeginning(stream); + using var reader = new BinaryReader(stream); + Assert.AreEqual(Dummydata, reader.ReadString()); + } + [TestMethod] public async Task DoNotFailWhenWritingOnADisposedBaseStream() { @@ -138,6 +166,162 @@ public async Task DoNotFailWhenReadingFromADisposedBaseStream() await _channel.NotifyDataAvailable(new CancellationToken()); } + [TestMethod] + public async Task SendShouldCloseStreamAndRejectLaterMessagesAfterPartialFrame() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + await Assert.ThrowsExactlyAsync(() => channel.Send(message)); + + Assert.HasCount(3, stream.WrittenBytes); + using (var prefixStream = new MemoryStream(stream.WrittenBytes)) + using (var prefixReader = new BinaryReader(prefixStream)) + { + Assert.AreEqual(message.Length, Read7BitEncodedInt(prefixReader)); + } + + var writeCallCount = stream.WriteCallCount; + await Assert.ThrowsExactlyAsync(() => channel.Send(Dummydata)); + + Assert.IsTrue(stream.IsDisposed); + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + Assert.HasCount(3, stream.WrittenBytes); + } + + /// + /// The corruption this change prevents, asserted at the peer instead of at the sender. A send + /// that fails once its length prefix has reached the peer leaves a frame header on the wire + /// promising a body that never arrives. On unmodified main the next message is consumed as that + /// body, and the peer decodes a string nobody ever sent, which is where the + /// "Unexpected character encountered while parsing value" JSON abort comes from. Every other + /// test here asserts what the sender does; this one asserts what the peer can observe. + /// + [TestMethod] + public async Task PeerShouldNotDecodeAMessageThatWasNeverSent() + { + var message1 = new string('a', SocketConstants.BufferSize + 1); + var message2 = new string('b', SocketConstants.BufferSize + 1); + + // The payload does not fit in what is left of the buffer, so the length prefix is flushed as + // its own write and reaches the peer before the payload write fails. + using var wire = new FailingWriteStream(bytesBeforeFailure: 3); + var sender = new LengthPrefixCommunicationChannel(wire); + + await Assert.ThrowsExactlyAsync(() => sender.Send(message1)); + + try + { + // The injected failure fires once, so on unmodified main this second message is written + // and lands directly behind the orphaned prefix. + await sender.Send(message2); + } + catch (CommunicationException) + { + // Expected once the channel refuses to send after a failed frame. + } + + var received = ReadFirstMessageFromWire(wire.WrittenBytes); + + var decoded = received is null ? string.Empty : DescribeFirstChars(received); + Assert.IsNull( + received, + $"The peer decoded a {received?.Length ?? 0} character frame that was never sent as a message, starting {decoded}."); + } + + private static string? ReadFirstMessageFromWire(byte[] bytesOnTheWire) + { + using var peerStream = new MemoryStream(bytesOnTheWire); + using var peer = new LengthPrefixCommunicationChannel(peerStream); + + string? received = null; + peer.MessageReceived.Subscribe((sender, messageEventArgs) => received = messageEventArgs.Data); + + try + { + peer.NotifyDataAvailable(CancellationToken.None).GetAwaiter().GetResult(); + } + catch (EndOfStreamException) + { + // An incomplete frame is the correct outcome. The peer has nothing to act on. + } + + return received; + } + + private static string DescribeFirstChars(string value) + { + var count = Math.Min(3, value.Length); + var parts = new string[count]; + for (var i = 0; i < count; i++) + { + parts[i] = $"U+{(int)value[i]:X4}"; + } + + return string.Join(" ", parts); + } + + [TestMethod] + public async Task DisposeShouldNotFlushBufferedDataAfterSendFailure() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 0); + var channel = new LengthPrefixCommunicationChannel(stream); + + await Assert.ThrowsExactlyAsync(() => channel.Send(Dummydata)); + var writeCallCount = stream.WriteCallCount; + + channel.Dispose(); + + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + } + + [TestMethod] + public async Task ConcurrentSendShouldNotWriteAfterFirstSendFails() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3, blockFirstWrite: true); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + var firstSend = Task.Run(() => channel.Send(message), TestContext.CancellationToken); + Assert.IsTrue(stream.WriteStarted.Wait(TimeSpan.FromSeconds(5), TestContext.CancellationToken)); + + var secondSend = Task.Run(() => channel.Send(Dummydata), TestContext.CancellationToken); + await Task.Delay(50, TestContext.CancellationToken); + Assert.IsFalse(secondSend.IsCompleted); + + stream.ReleaseWrite.Set(); + + await Assert.ThrowsExactlyAsync(() => firstSend); + await Assert.ThrowsExactlyAsync(() => secondSend); + Assert.IsTrue(stream.IsDisposed); + Assert.AreEqual(1, stream.WriteCallCount); + } + + [TestMethod] + public async Task DisposeShouldNeitherWriteNorBlockWhileASendIsInFlight() + { + using var stream = new FailingWriteStream(bytesBeforeFailure: 3, blockFirstWrite: true); + var channel = new LengthPrefixCommunicationChannel(stream); + var message = new string('x', SocketConstants.BufferSize + 1); + + var send = Task.Run(() => channel.Send(message), TestContext.CancellationToken); + Assert.IsTrue(stream.WriteStarted.Wait(TimeSpan.FromSeconds(5), TestContext.CancellationToken)); + + var writeCallCount = stream.WriteCallCount; + var stopwatch = Stopwatch.StartNew(); + channel.Dispose(); + stopwatch.Stop(); + + // The in-flight write is held for up to five seconds. Disposal must not wait for it, + // and must not flush the writer underneath it. + Assert.IsLessThan(TimeSpan.FromSeconds(2), stopwatch.Elapsed, $"Dispose blocked for {stopwatch.Elapsed}."); + Assert.AreEqual(writeCallCount, stream.WriteCallCount); + + stream.ReleaseWrite.Set(); + await Assert.ThrowsExactlyAsync(() => send); + } + // TODO // WriteFromMultilpleThreadShouldBeInSequence private static void SeekToBeginning(Stream stream) @@ -173,4 +357,77 @@ private static int Read7BitEncodedInt(BinaryReader reader) return count; } + + private sealed class FailingWriteStream : MemoryStream + { + private readonly int _bytesBeforeFailure; + private readonly bool _blockFirstWrite; + + private int _acceptedBytes; + private bool _failureInjected; + + public FailingWriteStream(int bytesBeforeFailure, bool blockFirstWrite = false) + { + _bytesBeforeFailure = bytesBeforeFailure; + _blockFirstWrite = blockFirstWrite; + } + + public bool IsDisposed { get; private set; } + + public int WriteCallCount { get; private set; } + + public byte[] WrittenBytes => ToArray(); + + public ManualResetEventSlim WriteStarted { get; } = new(false); + + public ManualResetEventSlim ReleaseWrite { get; } = new(false); + + public override void Write(byte[] buffer, int offset, int count) + { + if (IsDisposed) + { + throw new ObjectDisposedException(nameof(FailingWriteStream)); + } + + WriteCallCount++; + WriteStarted.Set(); + if (!_failureInjected) + { + if (_blockFirstWrite && !ReleaseWrite.Wait(TimeSpan.FromSeconds(5))) + { + throw new TimeoutException("Timed out waiting to release the injected write failure."); + } + + _failureInjected = true; + var remainingBytes = _bytesBeforeFailure - _acceptedBytes; + if (remainingBytes > 0) + { + var acceptedCount = Math.Min(remainingBytes, count); + base.Write(buffer, offset, acceptedCount); + _acceptedBytes += acceptedCount; + } + + throw new IOException("Injected write failure."); + } + + base.Write(buffer, offset, count); + } + + protected override void Dispose(bool disposing) + { + if (IsDisposed) + { + return; + } + + IsDisposed = true; + if (disposing) + { + WriteStarted.Dispose(); + ReleaseWrite.Dispose(); + } + + base.Dispose(disposing); + } + } }