| | 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() |
| 1793 | 18 | | { |
| 1793 | 19 | | _pipe.Writer.Complete(); |
| 1793 | 20 | | _pipe.Reader.Complete(); |
| 1793 | 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> |
| 1795 | 28 | | internal DuplexConnectionReader(IDuplexConnection connection, MemoryPool<byte> pool, int minimumSegmentSize) |
| 1795 | 29 | | { |
| 1795 | 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). |
| 1795 | 34 | | _pipe = new Pipe(new PipeOptions( |
| 1795 | 35 | | pool: pool, |
| 1795 | 36 | | minimumSegmentSize: minimumSegmentSize, |
| 1795 | 37 | | pauseWriterThreshold: 0, |
| 1795 | 38 | | useSynchronizationContext: false)); |
| 1795 | 39 | | } |
| | 40 | |
|
| 34953 | 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) |
| 24504 | 52 | | { |
| 24504 | 53 | | if (byteCount == 0) |
| 1017 | 54 | | { |
| 1017 | 55 | | return default; |
| | 56 | | } |
| | 57 | |
|
| | 58 | | // If there's still data on the pipe reader, copy the data from the pipe reader synchronously. |
| 23487 | 59 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| 23487 | 60 | | { |
| 23487 | 61 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| | 62 | |
|
| 23487 | 63 | | ReadOnlySequence<byte> buffer = readResult.Buffer; |
| 23487 | 64 | | if (buffer.Length > byteCount) |
| 6674 | 65 | | { |
| 6674 | 66 | | buffer = buffer.Slice(0, byteCount); |
| 6674 | 67 | | } |
| | 68 | |
|
| 23487 | 69 | | bufferWriter.Write(buffer); |
| 23487 | 70 | | _pipe.Reader.AdvanceTo(buffer.End); |
| | 71 | |
|
| 23487 | 72 | | byteCount -= (int)buffer.Length; |
| | 73 | |
|
| 23487 | 74 | | if (byteCount == 0) |
| 11425 | 75 | | { |
| 11425 | 76 | | return default; |
| | 77 | | } |
| 12062 | 78 | | } |
| | 79 | |
|
| 12062 | 80 | | return ReadFromConnectionAsync(byteCount); |
| | 81 | |
|
| | 82 | | // Read the remaining bytes directly from the connection into the buffer writer. |
| | 83 | | async ValueTask ReadFromConnectionAsync(int byteCount) |
| 12062 | 84 | | { |
| | 85 | | try |
| 12062 | 86 | | { |
| | 87 | | do |
| 111100 | 88 | | { |
| 111100 | 89 | | Memory<byte> buffer = bufferWriter.GetMemory(); |
| 111100 | 90 | | if (buffer.Length > byteCount) |
| 2234 | 91 | | { |
| 2234 | 92 | | buffer = buffer[0..byteCount]; |
| 2234 | 93 | | } |
| | 94 | |
|
| 111100 | 95 | | int read = await _connection.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); |
| 111094 | 96 | | bufferWriter.Advance(read); |
| 111094 | 97 | | byteCount -= read; |
| | 98 | |
|
| 111094 | 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 | | } |
| 111094 | 105 | | } |
| 111094 | 106 | | while (byteCount > 0); |
| 12056 | 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 | | } |
| 12056 | 115 | | } |
| 24504 | 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) => |
| 17067 | 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 |
| 9377 | 126 | | ReadAsyncCore(minimumSize: minimumSize, canReturnEmptyBuffer: false, cancellationToken); |
| | 127 | |
|
| | 128 | | internal bool TryRead(out ReadOnlySequence<byte> buffer) |
| 27278 | 129 | | { |
| 27278 | 130 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| 10211 | 131 | | { |
| 10211 | 132 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| 10211 | 133 | | buffer = readResult.Buffer; |
| 10211 | 134 | | return true; |
| | 135 | | } |
| | 136 | | else |
| 17067 | 137 | | { |
| 17067 | 138 | | buffer = default; |
| 17067 | 139 | | return false; |
| | 140 | | } |
| 27278 | 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) |
| 26444 | 150 | | { |
| 26444 | 151 | | Debug.Assert(minimumSize > 0); |
| | 152 | |
|
| | 153 | | // Read buffered data first. |
| 26444 | 154 | | if (_pipe.Reader.TryRead(out ReadResult readResult)) |
| 4501 | 155 | | { |
| 4501 | 156 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled && !readResult.Buffer.IsEmpty); |
| 4501 | 157 | | if (readResult.Buffer.Length >= minimumSize) |
| 4501 | 158 | | { |
| 4501 | 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 |
| 21943 | 166 | | { |
| | 167 | | do |
| 21943 | 168 | | { |
| | 169 | | // Fill the pipe with data read from the connection. |
| 21943 | 170 | | Memory<byte> buffer = _pipe.Writer.GetMemory(); |
| 21943 | 171 | | int read = await _connection.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); |
| | 172 | |
|
| 20682 | 173 | | _pipe.Writer.Advance(read); |
| 20682 | 174 | | minimumSize -= read; |
| | 175 | |
|
| | 176 | | // The peer shutdown its side of the connection, return an empty buffer if allowed. |
| 20682 | 177 | | if (read == 0) |
| 262 | 178 | | { |
| 262 | 179 | | if (canReturnEmptyBuffer) |
| 262 | 180 | | { |
| 262 | 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 | | } |
| 20420 | 190 | | } |
| 20420 | 191 | | while (minimumSize > 0); |
| 20682 | 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 | |
|
| 20682 | 201 | | _ = await _pipe.Writer.FlushAsync(cancellationToken).ConfigureAwait(false); |
| | 202 | |
|
| 20678 | 203 | | _pipe.Reader.TryRead(out readResult); |
| 20678 | 204 | | Debug.Assert(!readResult.IsCompleted && !readResult.IsCanceled); |
| | 205 | |
|
| 20678 | 206 | | return readResult.Buffer; |
| 25179 | 207 | | } |
| | 208 | | } |