| | | 1 | | // Copyright (c) ZeroC, Inc. |
| | | 2 | | |
| | | 3 | | using IceRpc.Internal; |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.IO.Pipelines; |
| | | 7 | | |
| | | 8 | | namespace IceRpc.Transports.Internal; |
| | | 9 | | |
| | | 10 | | /// <summary>A helper class to efficiently read data from a duplex connection. It provides a PipeReader-like API but is |
| | | 11 | | /// not a PipeReader. Like a PipeReader, its methods shouldn't be called concurrently.</summary> |
| | | 12 | | internal class DuplexConnectionReader : IDisposable |
| | | 13 | | { |
| | | 14 | | private readonly IDuplexConnection _connection; |
| | | 15 | | private readonly Pipe _pipe; |
| | | 16 | | |
| | | 17 | | public void Dispose() |
| | 1792 | 18 | | { |
| | 1792 | 19 | | _pipe.Writer.Complete(); |
| | 1792 | 20 | | _pipe.Reader.Complete(); |
| | 1792 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary>Constructs a duplex connection reader.</summary> |
| | | 24 | | /// <param name="connection">The duplex connection to reader from.</param> |
| | | 25 | | /// <param name="pool">The memory pool to use.</param> |
| | | 26 | | /// <param name="minimumSegmentSize">The minimum segment size for buffers allocated from <paramref name="pool"/>. |
| | | 27 | | /// </param> |
| | 1794 | 28 | | internal DuplexConnectionReader(IDuplexConnection connection, MemoryPool<byte> pool, int minimumSegmentSize) |
| | 1794 | 29 | | { |
| | 1794 | 30 | | _connection = connection; |
| | | 31 | | |
| | | 32 | | // The readerScheduler doesn't matter (we don't call _pipe.Reader.ReadAsync) and the writerScheduler doesn't |
| | | 33 | | // matter (_pipe.Writer.FlushAsync never blocks). |
| | 1794 | 34 | | _pipe = new Pipe(new PipeOptions( |
| | 1794 | 35 | | pool: pool, |
| | 1794 | 36 | | minimumSegmentSize: minimumSegmentSize, |
| | 1794 | 37 | | pauseWriterThreshold: 0, |
| | 1794 | 38 | | useSynchronizationContext: false)); |
| | 1794 | 39 | | } |
| | | 40 | | |
| | 35278 | 41 | | internal void AdvanceTo(SequencePosition consumed) => _pipe.Reader.AdvanceTo(consumed); |
| | | 42 | | |
| | | 43 | | internal void AdvanceTo(SequencePosition consumed, SequencePosition examined) => |
| | 161 | 44 | | _pipe.Reader.AdvanceTo(consumed, examined); |
| | | 45 | | |
| | | 46 | | /// <summary>Writes <paramref name="byteCount" /> bytes read from this pipe reader or its underlying connection |
| | | 47 | | /// into <paramref name="bufferWriter" />.</summary> |
| | | 48 | | internal ValueTask FillBufferWriterAsync( |
| | | 49 | | IBufferWriter<byte> bufferWriter, |
| | | 50 | | int byteCount, |
| | | 51 | | CancellationToken cancellationToken) |
| | 24568 | 52 | | { |
| | 24568 | 53 | | if (byteCount == 0) |
| | 1030 | 54 | | { |
| | 1030 | 55 | | return default; |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | // If there's still data on the pipe reader, copy the data from the pipe reader synchronously. |
| | 23538 | 59 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| | 23538 | 60 | | { |
| | 23538 | 61 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| | | 62 | | |
| | 23538 | 63 | | ReadOnlySequence<byte> buffer = readResult.Buffer; |
| | 23538 | 64 | | if (buffer.Length > byteCount) |
| | 6306 | 65 | | { |
| | 6306 | 66 | | buffer = buffer.Slice(0, byteCount); |
| | 6306 | 67 | | } |
| | | 68 | | |
| | 23538 | 69 | | bufferWriter.Write(buffer); |
| | 23538 | 70 | | _pipe.Reader.AdvanceTo(buffer.End); |
| | | 71 | | |
| | 23538 | 72 | | byteCount -= (int)buffer.Length; |
| | | 73 | | |
| | 23538 | 74 | | if (byteCount == 0) |
| | 11384 | 75 | | { |
| | 11384 | 76 | | return default; |
| | | 77 | | } |
| | 12154 | 78 | | } |
| | | 79 | | |
| | 12154 | 80 | | return ReadFromConnectionAsync(byteCount); |
| | | 81 | | |
| | | 82 | | // Read the remaining bytes directly from the connection into the buffer writer. |
| | | 83 | | async ValueTask ReadFromConnectionAsync(int byteCount) |
| | 12154 | 84 | | { |
| | | 85 | | try |
| | 12154 | 86 | | { |
| | | 87 | | do |
| | 95404 | 88 | | { |
| | 95404 | 89 | | Memory<byte> buffer = bufferWriter.GetMemory(); |
| | 95404 | 90 | | if (buffer.Length > byteCount) |
| | 2173 | 91 | | { |
| | 2173 | 92 | | buffer = buffer[0..byteCount]; |
| | 2173 | 93 | | } |
| | | 94 | | |
| | 95404 | 95 | | int read = await _connection.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); |
| | 95402 | 96 | | bufferWriter.Advance(read); |
| | 95402 | 97 | | byteCount -= read; |
| | | 98 | | |
| | 95402 | 99 | | if (byteCount > 0 && read == 0) |
| | 0 | 100 | | { |
| | | 101 | | // The peer gracefully shut down the connection but returned less data than expected, it's |
| | | 102 | | // considered as an error. |
| | 0 | 103 | | throw new InvalidDataException("Received less data than expected."); |
| | | 104 | | } |
| | 95402 | 105 | | } |
| | 95402 | 106 | | while (byteCount > 0); |
| | 12152 | 107 | | } |
| | 0 | 108 | | catch (ObjectDisposedException exception) |
| | 0 | 109 | | { |
| | 0 | 110 | | throw new IceRpcException( |
| | 0 | 111 | | IceRpcError.OperationAborted, |
| | 0 | 112 | | "The read operation was aborted by the disposal of the duplex connection.", |
| | 0 | 113 | | exception); |
| | | 114 | | } |
| | 12152 | 115 | | } |
| | 24568 | 116 | | } |
| | | 117 | | |
| | | 118 | | /// <summary>Reads and returns bytes from the underlying transport connection. The returned buffer can be empty if |
| | | 119 | | /// the peer shutdown its side of the connection.</summary> |
| | | 120 | | internal ValueTask<ReadOnlySequence<byte>> ReadAsync(CancellationToken cancellationToken = default) => |
| | 17925 | 121 | | ReadAsyncCore(minimumSize: 1, canReturnEmptyBuffer: true, cancellationToken); |
| | | 122 | | |
| | | 123 | | /// <summary>Reads and returns bytes from the underlying transport connection. The returned buffer has always |
| | | 124 | | /// at least minimumSize bytes.</summary> |
| | | 125 | | internal ValueTask<ReadOnlySequence<byte>> ReadAtLeastAsync(int minimumSize, CancellationToken cancellationToken = d |
| | 9475 | 126 | | ReadAsyncCore(minimumSize: minimumSize, canReturnEmptyBuffer: false, cancellationToken); |
| | | 127 | | |
| | | 128 | | internal bool TryRead(out ReadOnlySequence<byte> buffer) |
| | 27509 | 129 | | { |
| | 27509 | 130 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| | 9584 | 131 | | { |
| | 9584 | 132 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| | 9584 | 133 | | buffer = readResult.Buffer; |
| | 9584 | 134 | | return true; |
| | | 135 | | } |
| | | 136 | | else |
| | 17925 | 137 | | { |
| | 17925 | 138 | | buffer = default; |
| | 17925 | 139 | | return false; |
| | | 140 | | } |
| | 27509 | 141 | | } |
| | | 142 | | |
| | | 143 | | /// <summary>Reads and returns bytes from the underlying transport connection. The returned buffer has always at |
| | | 144 | | /// least minimumSize bytes or if canReturnEmptyBuffer is true, the returned buffer can be empty if the peer |
| | | 145 | | /// shutdown the connection.</summary> |
| | | 146 | | private async ValueTask<ReadOnlySequence<byte>> ReadAsyncCore( |
| | | 147 | | int minimumSize, |
| | | 148 | | bool canReturnEmptyBuffer, |
| | | 149 | | CancellationToken cancellationToken = default) |
| | 27400 | 150 | | { |
| | 27400 | 151 | | Debug.Assert(minimumSize > 0); |
| | | 152 | | |
| | | 153 | | // Read buffered data first. |
| | 27400 | 154 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| | 4710 | 155 | | { |
| | 4710 | 156 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| | 4710 | 157 | | if (readResult.Buffer.Length >= minimumSize) |
| | 4710 | 158 | | { |
| | 4710 | 159 | | return readResult.Buffer; |
| | | 160 | | } |
| | 0 | 161 | | _pipe.Reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End); |
| | 0 | 162 | | minimumSize -= (int)readResult.Buffer.Length; |
| | 0 | 163 | | } |
| | | 164 | | |
| | | 165 | | try |
| | 22690 | 166 | | { |
| | | 167 | | do |
| | 22690 | 168 | | { |
| | | 169 | | // Fill the pipe with data read from the connection. |
| | 22690 | 170 | | Memory<byte> buffer = _pipe.Writer.GetMemory(); |
| | 22690 | 171 | | int read = await _connection.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); |
| | | 172 | | |
| | 21432 | 173 | | _pipe.Writer.Advance(read); |
| | 21432 | 174 | | minimumSize -= read; |
| | | 175 | | |
| | | 176 | | // The peer shutdown its side of the connection, return an empty buffer if allowed. |
| | 21432 | 177 | | if (read == 0) |
| | 265 | 178 | | { |
| | 265 | 179 | | if (canReturnEmptyBuffer) |
| | 265 | 180 | | { |
| | 265 | 181 | | break; |
| | | 182 | | } |
| | | 183 | | else |
| | 0 | 184 | | { |
| | | 185 | | // The connection was aborted or the peer gracefully shut down the connection but returned less |
| | | 186 | | // data than expected. |
| | 0 | 187 | | throw new IceRpcException(IceRpcError.ConnectionAborted); |
| | | 188 | | } |
| | | 189 | | } |
| | 21167 | 190 | | } |
| | 21167 | 191 | | while (minimumSize > 0); |
| | 21432 | 192 | | } |
| | 0 | 193 | | catch (ObjectDisposedException exception) |
| | 0 | 194 | | { |
| | 0 | 195 | | throw new IceRpcException( |
| | 0 | 196 | | IceRpcError.OperationAborted, |
| | 0 | 197 | | "The read operation was aborted by the disposal of the duplex connection.", |
| | 0 | 198 | | exception); |
| | | 199 | | } |
| | | 200 | | |
| | 21432 | 201 | | _ = await _pipe.Writer.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | | 202 | | |
| | 21423 | 203 | | _pipe.Reader.TryRead(out readResult); |
| | 21423 | 204 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled); |
| | | 205 | | |
| | 21423 | 206 | | return readResult.Buffer; |
| | 26133 | 207 | | } |
| | | 208 | | } |