| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using System.Buffers; |
| | 4 | | using System.Diagnostics; |
| | 5 | | using System.IO.Pipelines; |
| | 6 | | using System.Net.Quic; |
| | 7 | | using System.Net.Sockets; |
| | 8 | |
|
| | 9 | | namespace IceRpc.Transports.Quic.Internal; |
| | 10 | |
|
| | 11 | | internal class QuicPipeWriter : ReadOnlySequencePipeWriter |
| | 12 | | { |
| 2 | 13 | | public override bool CanGetUnflushedBytes => true; |
| | 14 | |
|
| 2 | 15 | | public override long UnflushedBytes => _pipe.Writer.UnflushedBytes; |
| | 16 | |
|
| 24 | 17 | | internal Task Closed { get; } |
| | 18 | |
|
| | 19 | | private bool _isCompleted; |
| | 20 | | private readonly Action _completeCallback; |
| | 21 | | private readonly int _minSegmentSize; |
| | 22 | |
|
| | 23 | | // We use a helper Pipe instead of a StreamPipeWriter over _stream because StreamPipeWriter does not provide a |
| | 24 | | // WriteAsync with an endStream/completeWrites parameter while QuicStream does. |
| | 25 | | private readonly Pipe _pipe; |
| | 26 | | private readonly QuicStream _stream; |
| | 27 | |
|
| | 28 | | private readonly Action _throwIfConnectionClosedOrDisposed; |
| | 29 | |
|
| 14 | 30 | | public override void Advance(int bytes) => _pipe.Writer.Advance(bytes); |
| | 31 | |
|
| | 32 | | // QuicPipeWriter does not support this method: the IceRPC core does not need it. And when the application code |
| | 33 | | // installs a payload writer interceptor, this interceptor should never call it on "next". |
| 0 | 34 | | public override void CancelPendingFlush() => throw new NotSupportedException(); |
| | 35 | |
|
| | 36 | | public override void Complete(Exception? exception = null) |
| 1608 | 37 | | { |
| 1608 | 38 | | if (!_isCompleted) |
| 1004 | 39 | | { |
| 1004 | 40 | | if (exception is null && _pipe.Writer.UnflushedBytes > 0) |
| 2 | 41 | | { |
| 2 | 42 | | throw new InvalidOperationException( |
| 2 | 43 | | $"Completing a {nameof(QuicPipeWriter)} without an exception is not allowed when this pipe writer ha |
| | 44 | | } |
| | 45 | |
|
| 1002 | 46 | | _isCompleted = true; |
| | 47 | |
|
| 1002 | 48 | | if (exception is null) |
| 992 | 49 | | { |
| | 50 | | // Unlike Slic, it's important to complete the writes and not abort the stream. Data might still be |
| | 51 | | // buffered for send on the Quic stream and aborting the stream would discard this data. |
| 992 | 52 | | _stream.CompleteWrites(); |
| 992 | 53 | | } |
| | 54 | | else |
| 10 | 55 | | { |
| | 56 | | // We don't use the application error code, it's irrelevant. |
| 10 | 57 | | _stream.Abort(QuicAbortDirection.Write, errorCode: 0); |
| 10 | 58 | | } |
| | 59 | |
|
| 1002 | 60 | | _completeCallback(); |
| | 61 | |
|
| 1002 | 62 | | _pipe.Writer.Complete(); |
| 1002 | 63 | | _pipe.Reader.Complete(); |
| 1002 | 64 | | } |
| 1606 | 65 | | } |
| | 66 | |
|
| | 67 | | public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken) => |
| | 68 | | // WriteAsync will flush the internal buffer |
| 4 | 69 | | WriteAsync(ReadOnlySequence<byte>.Empty, endStream: false, cancellationToken); |
| | 70 | |
|
| 4 | 71 | | public override Memory<byte> GetMemory(int sizeHint) => _pipe.Writer.GetMemory(sizeHint); |
| | 72 | |
|
| 10 | 73 | | public override Span<byte> GetSpan(int sizeHint) => _pipe.Writer.GetSpan(sizeHint); |
| | 74 | |
|
| | 75 | | public override ValueTask<FlushResult> WriteAsync( |
| | 76 | | ReadOnlyMemory<byte> source, |
| | 77 | | CancellationToken cancellationToken) => |
| 11191 | 78 | | WriteAsync(new ReadOnlySequence<byte>(source), endStream: false, cancellationToken); |
| | 79 | |
|
| | 80 | | public override async ValueTask<FlushResult> WriteAsync( |
| | 81 | | ReadOnlySequence<byte> source, |
| | 82 | | bool endStream, |
| | 83 | | CancellationToken cancellationToken) |
| 11209 | 84 | | { |
| 11209 | 85 | | if (_isCompleted) |
| 0 | 86 | | { |
| 0 | 87 | | throw new InvalidOperationException("Writing is not allowed once the writer is completed."); |
| | 88 | | } |
| | 89 | |
|
| 11209 | 90 | | _throwIfConnectionClosedOrDisposed(); |
| | 91 | |
|
| | 92 | | try |
| 11205 | 93 | | { |
| 11205 | 94 | | if (_pipe.Writer.UnflushedBytes > 0) |
| 10 | 95 | | { |
| 10 | 96 | | if (!source.IsEmpty && source.Length < _minSegmentSize) |
| 6 | 97 | | { |
| | 98 | | // When source fits in the last segment of _pipe.Writer, we copy it into _pipe.Writer. |
| | 99 | |
|
| 6 | 100 | | Memory<byte> pipeMemory = _pipe.Writer.GetMemory(); |
| 6 | 101 | | if (source.Length <= pipeMemory.Length) |
| 4 | 102 | | { |
| 4 | 103 | | source.CopyTo(pipeMemory.Span); |
| 4 | 104 | | _pipe.Writer.Advance((int)source.Length); |
| 4 | 105 | | source = ReadOnlySequence<byte>.Empty; |
| 4 | 106 | | } |
| | 107 | | else |
| 2 | 108 | | { |
| 2 | 109 | | _pipe.Writer.Advance(0); |
| 2 | 110 | | } |
| 6 | 111 | | } |
| | 112 | |
|
| | 113 | | // Flush the internal pipe. |
| 10 | 114 | | FlushResult flushResult = await _pipe.Writer.FlushAsync(CancellationToken.None).ConfigureAwait(false); |
| 10 | 115 | | Debug.Assert(!flushResult.IsCanceled && !flushResult.IsCompleted); |
| | 116 | |
|
| | 117 | | // Read the data from the pipe. |
| 10 | 118 | | bool tryReadOk = _pipe.Reader.TryRead(out ReadResult readResult); |
| 10 | 119 | | Debug.Assert(tryReadOk); |
| 10 | 120 | | Debug.Assert(!readResult.IsCanceled && !readResult.IsCompleted && readResult.Buffer.Length > 0); |
| | 121 | |
|
| | 122 | | try |
| 10 | 123 | | { |
| | 124 | | // Write buffered data to the stream |
| 10 | 125 | | await WriteSequenceAsync( |
| 10 | 126 | | readResult.Buffer, |
| 10 | 127 | | completeWrites: endStream && source.IsEmpty, |
| 10 | 128 | | cancellationToken).ConfigureAwait(false); |
| 8 | 129 | | } |
| | 130 | | finally |
| 10 | 131 | | { |
| 10 | 132 | | _pipe.Reader.AdvanceTo(readResult.Buffer.End); |
| 10 | 133 | | } |
| | 134 | |
|
| 8 | 135 | | if (source.IsEmpty) |
| 6 | 136 | | { |
| | 137 | | // We're done, we don't want to write again an empty sequence. |
| 6 | 138 | | return new FlushResult(isCanceled: false, isCompleted: endStream); |
| | 139 | | } |
| 2 | 140 | | } |
| | 141 | |
|
| 11197 | 142 | | if (source.IsEmpty && !endStream) |
| 4 | 143 | | { |
| | 144 | | // Nothing to do; this typically corresponds to a call to FlushAsync when there was no unflushed bytes. |
| 4 | 145 | | return new FlushResult(isCanceled: false, isCompleted: false); |
| | 146 | | } |
| | 147 | | else |
| 11193 | 148 | | { |
| 11193 | 149 | | await WriteSequenceAsync(source, completeWrites: endStream, cancellationToken).ConfigureAwait(false); |
| 11181 | 150 | | return new FlushResult(isCanceled: false, isCompleted: endStream); |
| | 151 | | } |
| | 152 | | } |
| 12 | 153 | | catch (QuicException exception) when (exception.QuicError == QuicError.StreamAborted) |
| 8 | 154 | | { |
| 8 | 155 | | return new FlushResult(isCanceled: false, isCompleted: true); |
| | 156 | | } |
| 4 | 157 | | catch (QuicException exception) |
| 4 | 158 | | { |
| 4 | 159 | | throw exception.ToIceRpcException(); |
| | 160 | | } |
| 0 | 161 | | catch (SocketException exception) |
| 0 | 162 | | { |
| 0 | 163 | | throw exception.ToIceRpcException(); |
| | 164 | | } |
| | 165 | | // We don't wrap other exceptions |
| | 166 | |
|
| | 167 | | async ValueTask WriteSequenceAsync( |
| | 168 | | ReadOnlySequence<byte> sequence, |
| | 169 | | bool completeWrites, |
| | 170 | | CancellationToken cancellationToken) |
| 11203 | 171 | | { |
| 11203 | 172 | | if (sequence.IsSingleSegment) |
| 11199 | 173 | | { |
| 11199 | 174 | | await _stream.WriteAsync(sequence.First, completeWrites, cancellationToken).ConfigureAwait(false); |
| 11185 | 175 | | } |
| | 176 | | else |
| 4 | 177 | | { |
| 4 | 178 | | ReadOnlySequence<byte>.Enumerator enumerator = sequence.GetEnumerator(); |
| 4 | 179 | | bool hasMore = enumerator.MoveNext(); |
| 4 | 180 | | Debug.Assert(hasMore); |
| | 181 | | do |
| 10 | 182 | | { |
| 10 | 183 | | ReadOnlyMemory<byte> buffer = enumerator.Current; |
| 10 | 184 | | hasMore = enumerator.MoveNext(); |
| 10 | 185 | | await _stream.WriteAsync(buffer, completeWrites: completeWrites && !hasMore, cancellationToken) |
| 10 | 186 | | .ConfigureAwait(false); |
| 10 | 187 | | } |
| 10 | 188 | | while (hasMore); |
| 4 | 189 | | } |
| 11189 | 190 | | } |
| 11199 | 191 | | } |
| | 192 | |
|
| 1042 | 193 | | internal QuicPipeWriter( |
| 1042 | 194 | | QuicStream stream, |
| 1042 | 195 | | MemoryPool<byte> pool, |
| 1042 | 196 | | int minSegmentSize, |
| 1042 | 197 | | Action completeCallback, |
| 1042 | 198 | | Action throwIfConnectionClosedOrDisposed) |
| 1042 | 199 | | { |
| 1042 | 200 | | _stream = stream; |
| 1042 | 201 | | _minSegmentSize = minSegmentSize; |
| 1042 | 202 | | _completeCallback = completeCallback; |
| | 203 | |
|
| | 204 | | // This callback is used to check if the connection is closed or disposed before calling WriteAsync on the Quic |
| | 205 | | // stream. This check works around the use of the QuicError.OperationAborted error code for both reporting the |
| | 206 | | // abortion of the in-progress write call and for reporting a closed connection before the operation process |
| | 207 | | // starts. In this latter case, we want to report ConnectionAborted. |
| 1042 | 208 | | _throwIfConnectionClosedOrDisposed = throwIfConnectionClosedOrDisposed; |
| | 209 | |
|
| | 210 | | // Create a pipe that never pauses on flush or write. The Quic _stream.WriteAsync will block if the Quic flow |
| | 211 | | // control doesn't permit sending more data. |
| | 212 | | // The readerScheduler doesn't matter (we don't call _pipe.Reader.ReadAsync) and the writerScheduler doesn't |
| | 213 | | // matter (_pipe.Writer.FlushAsync never blocks). |
| 1042 | 214 | | _pipe = new(new PipeOptions( |
| 1042 | 215 | | pool: pool, |
| 1042 | 216 | | minimumSegmentSize: minSegmentSize, |
| 1042 | 217 | | pauseWriterThreshold: 0, |
| 1042 | 218 | | useSynchronizationContext: false)); |
| | 219 | |
|
| 1042 | 220 | | Closed = ClosedAsync(); |
| | 221 | |
|
| | 222 | | async Task ClosedAsync() |
| 1042 | 223 | | { |
| | 224 | | try |
| 1042 | 225 | | { |
| 1042 | 226 | | await _stream.WritesClosed.ConfigureAwait(false); |
| 816 | 227 | | } |
| 226 | 228 | | catch |
| 226 | 229 | | { |
| | 230 | | // Ignore failures. |
| 226 | 231 | | } |
| 1042 | 232 | | } |
| 1042 | 233 | | } |
| | 234 | | } |