Ejemplo n.º 1
0
        public Task CopyToAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            CheckDisposed();
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            try
            {
                ArraySegment <byte> buffer;
                if (TryGetBuffer(out buffer))
                {
                    return(CopyToAsyncCore(stream.WriteAsync(new ReadOnlyMemory <byte>(buffer.Array, buffer.Offset, buffer.Count), cancellationToken)));
                }
                else
                {
                    Task task = SerializeToStreamAsync(stream, context, cancellationToken);
                    CheckTaskNotNull(task);
                    return(CopyToAsyncCore(new ValueTask(task)));
                }
            }
            catch (Exception e) when(StreamCopyExceptionNeedsWrapping(e))
            {
                return(Task.FromException(GetStreamCopyException(e)));
            }
        }
Ejemplo n.º 2
0
        // for-each content
        //   write "--" + boundary
        //   for-each content header
        //     write header: header-value
        //   write content.CopyTo[Async]
        // write "--" + boundary + "--"
        // Can't be canceled directly by the user.  If the overall request is canceled
        // then the stream will be closed an exception thrown.
        protected override void SerializeToStream(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            Debug.Assert(stream != null);
            try
            {
                // Write start boundary.
                WriteToStream(stream, "--" + _boundary + CrLf);

                // Write each nested content.
                for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++)
                {
                    // Write divider, headers, and content.
                    HttpContent content = _nestedContent[contentIndex];
                    SerializeHeadersToStream(stream, content, writeDivider: contentIndex != 0);
                    content.CopyTo(stream, context, cancellationToken);
                }

                // Write footer boundary.
                WriteToStream(stream, CrLf + "--" + _boundary + "--" + CrLf);
            }
            catch (Exception ex)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(this, ex);
                }
                throw;
            }
        }
 protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
 {
     // don't let StreamWriter close the stream
     using var wrappingStream = new WrappingStream(stream, Ownership.None);
     using var writer         = new StreamWriter(wrappingStream);
     await writer.WriteAsync(Json).ConfigureAwait(false);
 }
Ejemplo n.º 4
0
        // for-each content
        //   write "--" + boundary
        //   for-each content header
        //     write header: header-value
        //   write content.CopyTo[Async]
        // write "--" + boundary + "--"
        // Can't be canceled directly by the user.  If the overall request is canceled
        // then the stream will be closed an exception thrown.
        protected override void SerializeToStream(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            Debug.Assert(stream != null);
            try
            {
                // Write start boundary.
                EncodeStringToStream(stream, "--" + _boundary + CrLf);

                // Write each nested content.
                var output = new StringBuilder();
                for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++)
                {
                    // Write divider, headers, and content.
                    HttpContent content = _nestedContent[contentIndex];
                    EncodeStringToStream(stream, SerializeHeadersToString(output, contentIndex, content));
                    content.CopyTo(stream, context, cancellationToken);
                }

                // Write footer boundary.
                EncodeStringToStream(stream, CrLf + "--" + _boundary + "--" + CrLf);
            }
            catch (Exception ex)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(this, ex);
                }
                throw;
            }
        }
Ejemplo n.º 5
0
 protected override void SerializeToStream(Stream stream, TransportContext?context, CancellationToken cancellationToken)
 {
     Debug.Assert(stream != null);
     PrepareContent();
     // If the stream can't be re-read, make sure that it gets disposed once it is consumed.
     StreamToStreamCopy.Copy(_content, stream, _bufferSize, !_content.CanSeek);
 }
Ejemplo n.º 6
0
        private protected async Task SerializeToStreamAsyncCore(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            Debug.Assert(stream != null);
            try
            {
                // Write start boundary.
                await EncodeStringToStreamAsync(stream, "--" + _boundary + CrLf, cancellationToken).ConfigureAwait(false);

                // Write each nested content.
                var output = new StringBuilder();
                for (int contentIndex = 0; contentIndex < _nestedContent.Count; contentIndex++)
                {
                    // Write divider, headers, and content.
                    HttpContent content = _nestedContent[contentIndex];
                    await EncodeStringToStreamAsync(stream, SerializeHeadersToString(output, contentIndex, content), cancellationToken).ConfigureAwait(false);

                    await content.CopyToAsync(stream, context, cancellationToken).ConfigureAwait(false);
                }

                // Write footer boundary.
                await EncodeStringToStreamAsync(stream, CrLf + "--" + _boundary + "--" + CrLf, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Error(this, ex);
                }
                throw;
            }
        }
Ejemplo n.º 7
0
 protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
 {
     using (Stream decompressedStream = TryCreateContentReadStream() ?? await CreateContentReadStreamAsync(cancellationToken).ConfigureAwait(false))
     {
         await decompressedStream.CopyToAsync(stream, cancellationToken).ConfigureAwait(false);
     }
 }
        Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            Debug.Assert(stream != null);

            if (_contentConsumed)
            {
                throw new InvalidOperationException(SR.net_http_content_stream_already_read);
            }
            _contentConsumed = true;

            const int BufferSize = 8192;
            Task      copyTask   = _content.CopyToAsync(stream, BufferSize, cancellationToken);

            if (copyTask.IsCompleted)
            {
                try { _content.Dispose(); } catch { } // same as StreamToStreamCopy behavior
            }
            else
            {
                copyTask = copyTask.ContinueWith((t, s) =>
                {
                    try { ((Stream)s !).Dispose(); } catch { }
                    t.GetAwaiter().GetResult();
                }, _content, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
            }
            return(copyTask);
        }
Ejemplo n.º 9
0
                protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
                {
                    _innerStream = await _inner.ReadAsStreamAsync().ConfigureAwait(false);

                    _innerStream = new PauseStream(_innerStream);

                    await _innerStream.CopyToAsync(stream).ConfigureAwait(false);
                }
Ejemplo n.º 10
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            var contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);

            var decompressedLength = await compressor.DecompressAsync(contentStream, stream).ConfigureAwait(false);

            Headers.ContentLength = decompressedLength;
        }
Ejemplo n.º 11
0
        protected sealed override async Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            Debug.Assert(stream != null);

            using (Stream contentStream = ConsumeStream())
            {
                const int BufferSize = 8192;
                await contentStream.CopyToAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 12
0
        protected override void SerializeToStream(Stream stream, TransportContext?context,
                                                  CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(stream);

            using (Stream contentStream = ConsumeStream())
            {
                const int BufferSize = 8192;
                contentStream.CopyTo(stream, BufferSize);
            }
        }
Ejemplo n.º 13
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            var writeMessageTask = _call.WriteMessageAsync(stream, _content, _call.Options);

            if (writeMessageTask.IsCompletedSuccessfully)
            {
                GrpcEventSource.Log.MessageSent();
                return(Task.CompletedTask);
            }

            return(WriteMessageCore(writeMessageTask));
        }
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            // Immediately flush request stream to send headers
            // https://github.com/dotnet/corefx/issues/39586#issuecomment-516210081
            await stream.FlushAsync().ConfigureAwait(false);

            // Pass request stream to writer
            _streamWriter.WriteStreamTcs.TrySetResult(stream);

            // Wait for the writer to report it is complete
            await _streamWriter.CompleteTcs.Task.ConfigureAwait(false);
        }
Ejemplo n.º 15
0
 protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
 {
     try
     {
         await _envelope.SerializeAsync(stream, _logger).ConfigureAwait(false);
     }
     catch (Exception e)
     {
         _logger?.LogError("Failed to serialize Envelope into the network stream", e);
         throw;
     }
 }
Ejemplo n.º 16
0
 public Task CopyToAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
 {
     CheckDisposed();
     ArgumentNullException.ThrowIfNull(stream);
     try
     {
         return(WaitAsync(InternalCopyToAsync(stream, context, cancellationToken)));
     }
     catch (Exception e) when(StreamCopyExceptionNeedsWrapping(e))
     {
         return(Task.FromException(GetStreamCopyException(e)));
     }
Ejemplo n.º 17
0
        protected sealed override async Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (Stream contentStream = ConsumeStream())
            {
                const int BufferSize = 8192;
                await contentStream.CopyToAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 18
0
            protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
            {
                var gzipStream = new GZipStream(stream, _compressionLevel, leaveOpen: true);

                try
                {
                    await _content.CopyToAsync(gzipStream).ConfigureAwait(false);
                }
                finally
                {
                    gzipStream.Dispose();
                }
            }
Ejemplo n.º 19
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
#pragma warning disable CA2012 // Use ValueTasks correctly
            var writeMessageTask = _startCallback(_request, stream);
#pragma warning restore CA2012 // Use ValueTasks correctly
            if (writeMessageTask.IsCompletedSuccessfully())
            {
                GrpcEventSource.Log.MessageSent();
                return(Task.CompletedTask);
            }

            return(WriteMessageCore(writeMessageTask));
        }
Ejemplo n.º 20
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            if (_payload == null)
            {
                _payload = SerializePayload();
            }

            await _call.WriteMessageAsync(
                stream,
                _payload,
                _call.Options).ConfigureAwait(false);

            GrpcEventSource.Log.MessageSent();
        }
Ejemplo n.º 21
0
        protected override void SerializeToStream(Stream stream, TransportContext?context,
                                                  CancellationToken cancellationToken)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (Stream contentStream = ConsumeStream())
            {
                const int BufferSize = 8192;
                contentStream.CopyTo(stream, BufferSize);
            }
        }
Ejemplo n.º 22
0
        protected sealed override Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(stream);
            return(Impl(stream, context, cancellationToken));

            async Task Impl(Stream stream, TransportContext?context, CancellationToken cancellationToken)
            {
                using (Stream contentStream = ConsumeStream())
                {
                    const int BufferSize = 8192;
                    await contentStream.CopyToAsync(stream, BufferSize, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Ejemplo n.º 23
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
#pragma warning disable CA2012 // Use ValueTasks correctly
            var writeMessageTask = _call.WriteMessageAsync(
                stream,
                _content,
                _call.Method.RequestMarshaller.ContextualSerializer,
                _call.Options);
#pragma warning restore CA2012 // Use ValueTasks correctly
            if (writeMessageTask.IsCompletedSuccessfully())
            {
                GrpcEventSource.Log.MessageSent();
                return(Task.CompletedTask);
            }

            return(WriteMessageCore(writeMessageTask));
        }
Ejemplo n.º 24
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context)
        {
            ReadOnlyMemory<byte> buffer = _content.AsMemoryBytes();
            if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
            {
                await stream.WriteAsync(array.Array, array.Offset, array.Count).ConfigureAwait(false);
            }
            else
            {
                byte[] localBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
                buffer.Span.CopyTo(localBuffer);

                await stream.WriteAsync(localBuffer, 0, buffer.Length).ConfigureAwait(false);

                ArrayPool<byte>.Shared.Return(localBuffer);
            }
        }
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            // This method will only be called by tests when response content is
            // accessed via ReadAsBytesAsync. The gRPC client will always
            // call ReadAsStreamAsync, which will call CreateContentReadStreamAsync.

            _innerStream = await _inner.ReadAsStreamAsync().ConfigureAwait(false);

            if (_mode == GrpcWebMode.GrpcWebText)
            {
                _innerStream = new Base64ResponseStream(_innerStream);
            }

            _innerStream = new GrpcWebResponseStream(_innerStream, _responseTrailers);

            await _innerStream.CopyToAsync(stream).ConfigureAwait(false);
        }
Ejemplo n.º 26
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            if (_pooledContentStream?.Length > 0)
            {
                await _pooledContentStream.CopyToAsync(stream).ConfigureAwait(false);

                return;
            }

            // Pooled buffer may seems redundant while reviewing current method, but when passed to json writer it completely changes the write logic.
            // Instead of reallocating new in-memory arrays when json size grows and Flush is not called explicitly - it now uses pooled buffer.
            // With proper flushing logic amount of buffer growths/copies should be zero and amount of memory allocations should be zero as well.
            using var bufferWriter = new PooledByteBufferWriter(stream);
            await using var writer = new Utf8JsonWriter(bufferWriter, JsonWriterOptions);
            var ddbWriter = new DdbWriter(writer, bufferWriter);

            await WriteDataAsync(ddbWriter).ConfigureAwait(false);

            await ddbWriter.FlushAsync().ConfigureAwait(false);
        }
Ejemplo n.º 27
0
 public void CopyTo(Stream stream, TransportContext?context, CancellationToken cancellationToken)
 {
     CheckDisposed();
     ArgumentNullException.ThrowIfNull(stream);
     try
     {
         if (TryGetBuffer(out ArraySegment <byte> buffer))
         {
             stream.Write(buffer.Array !, buffer.Offset, buffer.Count);
         }
         else
         {
             SerializeToStream(stream, context, cancellationToken);
         }
     }
     catch (Exception e) when(StreamCopyExceptionNeedsWrapping(e))
     {
         throw GetStreamCopyException(e);
     }
 }
Ejemplo n.º 28
0
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context)
        {
            var buffer       = new byte[bufferSize];
            var toUploadSize = this.uploadSize;

            while (toUploadSize > 0)
            {
                var sizeToRead = Math.Min(toUploadSize, bufferSize);
                var readSize   = await this.content.ReadAsync(buffer, 0, sizeToRead);

                if (readSize <= 0)
                {
                    this.ContentEnded = true;
                    break;
                }

                await stream.WriteAsync(buffer, 0, readSize);

                this.UploadedSize += readSize;
                toUploadSize      -= readSize;
            }
        }
Ejemplo n.º 29
0
 protected override Task SerializeToStreamAsync(Stream stream, TransportContext?context, CancellationToken cancellationToken) =>
 // Only skip the original protected virtual SerializeToStreamAsync if this
 // isn't a derived type that may have overridden the behavior.
 GetType() == typeof(ByteArrayContent) ? SerializeToStreamAsyncCore(stream, cancellationToken) :
 base.SerializeToStreamAsync(stream, context, cancellationToken);
Ejemplo n.º 30
0
 protected override Task SerializeToStreamAsync(Stream stream, TransportContext?context) =>
 SerializeToStreamAsyncCore(stream, default);