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