| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using Google.Protobuf; |
| | 4 | | using System.Buffers; |
| | 5 | | using System.Buffers.Binary; |
| | 6 | | using System.Diagnostics; |
| | 7 | | using System.IO.Pipelines; |
| | 8 | |
|
| | 9 | | namespace IceRpc.Protobuf.Internal; |
| | 10 | |
|
| | 11 | | /// <summary>Provides an extension method for <see cref="IAsyncEnumerable{T}" /> to encode elements into a <see |
| | 12 | | /// cref="PipeReader"/>.</summary> |
| | 13 | | internal static class AsyncEnumerableExtensions |
| | 14 | | { |
| | 15 | | /// <summary>Encodes an async enumerable into a stream of bytes represented by a <see cref="PipeReader"/>.</summary> |
| | 16 | | /// <typeparam name="T">The async enumerable element type.</typeparam> |
| | 17 | | /// <param name="asyncEnumerable">The async enumerable to encode into a stream of bytes.</param> |
| | 18 | | /// <param name="encodeOptions">The Protobuf encode options.</param> |
| | 19 | | /// <returns>A pipe reader that represents the encoded stream of bytes.</returns> |
| | 20 | | /// <remarks>This extension method is used to encode streaming parameters and streaming return values.</remarks> |
| | 21 | | internal static PipeReader ToPipeReader<T>( |
| | 22 | | this IAsyncEnumerable<T> asyncEnumerable, |
| | 23 | | ProtobufEncodeOptions? encodeOptions = null) where T : IMessage<T> => |
| 26 | 24 | | new AsyncEnumerablePipeReader<T>(asyncEnumerable, encodeOptions); |
| | 25 | |
|
| | 26 | | // Overriding ReadAtLeastAsyncCore or CopyToAsync methods for this reader is not critical since this reader is |
| | 27 | | // mostly used by the IceRPC core to copy the encoded data for the enumerable to the network stream. This copy |
| | 28 | | // doesn't use these methods. |
| | 29 | | #pragma warning disable CA1001 // Types that own disposable fields should be disposable. |
| | 30 | | private class AsyncEnumerablePipeReader<T> : PipeReader where T : IMessage<T> |
| | 31 | | #pragma warning restore CA1001 |
| | 32 | | { |
| | 33 | | // Disposed in Complete. |
| | 34 | | private readonly IAsyncEnumerator<T> _asyncEnumerator; |
| | 35 | |
|
| | 36 | | // We don't dispose _cts because it's not necessary |
| | 37 | | // (see https://github.com/dotnet/runtime/issues/29970#issuecomment-717840778) and we can't easily dispose it |
| | 38 | | // when no one is using it since CancelPendingRead can be called by another thread after Complete is called. |
| 26 | 39 | | private readonly CancellationTokenSource _cts = new(); |
| | 40 | | private bool _isCompleted; |
| | 41 | | private readonly int _streamFlushThreshold; |
| | 42 | | private Task<bool>? _moveNext; |
| | 43 | | private readonly Pipe _pipe; |
| | 44 | |
|
| 131449 | 45 | | public override void AdvanceTo(SequencePosition consumed) => _pipe.Reader.AdvanceTo(consumed); |
| | 46 | |
|
| | 47 | | public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) => |
| 0 | 48 | | _pipe.Reader.AdvanceTo(consumed, examined); |
| | 49 | |
|
| | 50 | | public override void CancelPendingRead() |
| 1 | 51 | | { |
| 1 | 52 | | _pipe.Reader.CancelPendingRead(); |
| 1 | 53 | | _cts.Cancel(); |
| 1 | 54 | | } |
| | 55 | |
|
| | 56 | | public override void Complete(Exception? exception = null) |
| 26 | 57 | | { |
| 26 | 58 | | if (!_isCompleted) |
| 22 | 59 | | { |
| 22 | 60 | | _isCompleted = true; |
| | 61 | |
|
| | 62 | | // Cancel MoveNextAsync if it's still running. |
| 22 | 63 | | _cts.Cancel(); |
| | 64 | |
|
| 22 | 65 | | _pipe.Reader.Complete(); |
| 22 | 66 | | _pipe.Writer.Complete(); |
| | 67 | |
|
| 22 | 68 | | _ = DisposeEnumeratorAsync(); |
| 22 | 69 | | } |
| | 70 | |
|
| | 71 | | async Task DisposeEnumeratorAsync() |
| 22 | 72 | | { |
| | 73 | | // Make sure MoveNextAsync is completed before disposing the enumerator. Calling DisposeAsync on the |
| | 74 | | // enumerator while MoveNextAsync is still running is disallowed. |
| 22 | 75 | | if (_moveNext is not null) |
| 2 | 76 | | { |
| | 77 | | try |
| 2 | 78 | | { |
| 2 | 79 | | _ = await _moveNext.ConfigureAwait(false); |
| 0 | 80 | | } |
| 2 | 81 | | catch |
| 2 | 82 | | { |
| 2 | 83 | | } |
| 2 | 84 | | } |
| 22 | 85 | | await _asyncEnumerator.DisposeAsync().ConfigureAwait(false); |
| 22 | 86 | | } |
| 26 | 87 | | } |
| | 88 | |
|
| | 89 | | public override async ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) |
| 131463 | 90 | | { |
| 131463 | 91 | | if (!_pipe.Reader.TryRead(out ReadResult readResult)) |
| 147 | 92 | | { |
| | 93 | | // If no more buffered data to read, fill the pipe with new data. |
| | 94 | |
|
| | 95 | | // If ReadAsync is canceled, cancel the enumerator iteration to ensure MoveNextAsync below completes. |
| 147 | 96 | | using CancellationTokenRegistration registration = cancellationToken.UnsafeRegister( |
| 1 | 97 | | cts => ((CancellationTokenSource)cts!).Cancel(), |
| 147 | 98 | | _cts); |
| | 99 | |
|
| | 100 | | bool hasNext; |
| | 101 | | try |
| 147 | 102 | | { |
| 147 | 103 | | if (_moveNext is null) |
| 21 | 104 | | { |
| 21 | 105 | | hasNext = await _asyncEnumerator.MoveNextAsync().ConfigureAwait(false); |
| 19 | 106 | | } |
| | 107 | | else |
| 126 | 108 | | { |
| 126 | 109 | | hasNext = await _moveNext.ConfigureAwait(false); |
| 125 | 110 | | _moveNext = null; |
| 125 | 111 | | } |
| | 112 | |
|
| 144 | 113 | | if (hasNext && EncodeElements() is Task<bool> moveNext) |
| 127 | 114 | | { |
| | 115 | | // Flush does not block because the pipe is configured to not pause flush. |
| 127 | 116 | | ValueTask<FlushResult> valueTask = _pipe.Writer.FlushAsync(CancellationToken.None); |
| 127 | 117 | | Debug.Assert(valueTask.IsCompletedSuccessfully); |
| | 118 | |
|
| 127 | 119 | | _moveNext = moveNext; |
| | 120 | | // And the next ReadAsync will await _moveNext. |
| 127 | 121 | | } |
| | 122 | | else |
| 17 | 123 | | { |
| | 124 | | // No need to flush the writer, complete takes care of it. |
| 17 | 125 | | _pipe.Writer.Complete(); |
| 17 | 126 | | } |
| | 127 | |
|
| | 128 | | // There are bytes in the reader or it's completed since we've just flushed or completed the writer. |
| 144 | 129 | | bool ok = _pipe.Reader.TryRead(out readResult); |
| 144 | 130 | | Debug.Assert(ok); |
| 144 | 131 | | } |
| 2 | 132 | | catch (OperationCanceledException exception) |
| 2 | 133 | | { |
| 2 | 134 | | Debug.Assert(exception.CancellationToken == _cts.Token); |
| 2 | 135 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 136 | |
|
| 1 | 137 | | if (_pipe.Reader.TryRead(out readResult) && readResult.IsCanceled) |
| 1 | 138 | | { |
| | 139 | | // Ok: return canceled readResult once after calling CancelPendingRead. |
| | 140 | | // Note that we can't return a canceled read result with a bogus buffer since the caller must |
| | 141 | | // be able to call reader.AdvanceTo with this buffer. |
| 1 | 142 | | } |
| | 143 | | else |
| 0 | 144 | | { |
| 0 | 145 | | throw new NotSupportedException( |
| 0 | 146 | | "Cannot resume reading an AsyncEnumerablePipeReader after canceling a ReadAsync or calling C |
| | 147 | | } |
| 1 | 148 | | } |
| 145 | 149 | | } |
| | 150 | |
|
| 131461 | 151 | | return readResult; |
| | 152 | |
|
| | 153 | | Task<bool>? EncodeElements() |
| 143 | 154 | | { |
| 143 | 155 | | Task<bool>? result = null; |
| | 156 | | bool keepEncoding; |
| 143 | 157 | | int written = 0; |
| | 158 | | do |
| 65778 | 159 | | { |
| 65778 | 160 | | _pipe.Writer.Write(new Span<byte>([0])); // Not compressed |
| 65778 | 161 | | Span<byte> lengthPlaceholder = _pipe.Writer.GetSpan(4)[..4]; |
| 65778 | 162 | | _pipe.Writer.Advance(4); |
| 65778 | 163 | | _asyncEnumerator.Current.WriteTo(_pipe.Writer); |
| 65778 | 164 | | int length = checked((int)_pipe.Writer.UnflushedBytes - written); |
| 65778 | 165 | | written += length; |
| 65778 | 166 | | BinaryPrimitives.WriteInt32BigEndian(lengthPlaceholder, length - 5); |
| 65778 | 167 | | ValueTask<bool> moveNext = _asyncEnumerator.MoveNextAsync(); |
| | 168 | |
|
| 65778 | 169 | | if (moveNext.IsCompletedSuccessfully) |
| 65745 | 170 | | { |
| 65745 | 171 | | bool hasNext = moveNext.Result; |
| | 172 | |
|
| | 173 | | // If we reached the stream flush threshold, it's time to flush. |
| 65745 | 174 | | if (written >= _streamFlushThreshold) |
| 94 | 175 | | { |
| 94 | 176 | | result = hasNext ? moveNext.AsTask() : null; |
| 94 | 177 | | keepEncoding = false; |
| 94 | 178 | | } |
| | 179 | | else |
| 65651 | 180 | | { |
| 65651 | 181 | | keepEncoding = hasNext; |
| 65651 | 182 | | } |
| 65745 | 183 | | } |
| | 184 | | else |
| 33 | 185 | | { |
| | 186 | | // If we can't get the next element synchronously, we return the move next task and end the loop |
| | 187 | | // to flush the encoded elements. |
| 33 | 188 | | result = moveNext.AsTask(); |
| 33 | 189 | | keepEncoding = false; |
| 33 | 190 | | } |
| 65778 | 191 | | } |
| 65778 | 192 | | while (keepEncoding); |
| 143 | 193 | | return result; |
| 143 | 194 | | } |
| 131461 | 195 | | } |
| | 196 | |
|
| 0 | 197 | | public override bool TryRead(out ReadResult result) => _pipe.Reader.TryRead(out result); |
| | 198 | |
|
| 26 | 199 | | internal AsyncEnumerablePipeReader( |
| 26 | 200 | | IAsyncEnumerable<T> asyncEnumerable, |
| 26 | 201 | | ProtobufEncodeOptions? encodeOptions) |
| 26 | 202 | | { |
| 26 | 203 | | encodeOptions ??= ProtobufEncodeOptions.Default; |
| 26 | 204 | | _pipe = new Pipe(encodeOptions.PipeOptions); |
| 26 | 205 | | _streamFlushThreshold = encodeOptions.StreamFlushThreshold; |
| 26 | 206 | | _asyncEnumerator = asyncEnumerable.GetAsyncEnumerator(_cts.Token); |
| 26 | 207 | | } |
| | 208 | | } |
| | 209 | | } |