protected virtual async Task <ImageInfo> InvokeGetImageInfoAsync(
            IImageSource source,
            string endpoint,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            using var scope = Logger.BeginScope(Guid.NewGuid());
            Logger.LogDebug("Analyze operation starting.");
            var uri     = new UriBuilder(endpoint).AppendPathSegment(Routes.Info).Uri;
            var context = await GetOperationContextAsync(source, endpoint, cancellationToken);

            Logger.LogDebug("Computed context for analyze operation ({0}).", context.ContentType);
            try
            {
                var consumer = StreamConsumer.Create((input, cancellationToken) => JsonSerializer.DeserializeAsync <ImageInfo>(input, _imageInfoOptions, cancellationToken))
                               .Chain(StreamTransformation.Create(async(input, output, cancellationToken) =>
                {
                    Logger.LogDebug("Sending analyze request.");
                    using var request = new HttpRequestMessage(HttpMethod.Post, uri)
                          {
                              Content = new TypedStreamContent(input, context.ContentType)
                          };
                    using var client   = CreateHttpClient();
                    using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
                    Logger.LogDebug("Received response of the analyze request.");
                    await CheckAsync(response, cancellationToken);
                    using var stream = await response.Content.ReadAsStreamAsync();
                    await stream.CopyToAsync(output, 16 * 1024, cancellationToken);
                    Logger.LogDebug("Done processing response of the analyze request.");
                }));
                Logger.LogDebug("Initializing analyze operation.");
                var result = await context.Producer.ConsumeAsync(consumer, cancellationToken).ConfigureAwait(false);

                Logger.LogDebug("Analyze operation completed.");
                return(result);
            }
            catch (Exception exn) when(!(exn is ImageException))
            {
                if (IsSocketRelated(exn, out var socketExn))
                {
                    if (IsBrokenPipe(socketExn) && source.Reusable)
                    {
                        Logger.LogWarning(exn, "Failed to perform operation due to connection error, retrying...");
                        return(await InvokeGetImageInfoAsync(source, endpoint, cancellationToken));
                    }
                    throw new RemoteImageConnectivityException(endpoint, socketExn.SocketErrorCode, "Network related error has occured while performing operation.", exn);
                }
                throw new RemoteImageException(endpoint, ErrorCodes.GenericError, "Error has occurred while performing operation.", exn);
            }
        }
Exemple #2
0
        public async Task StreamInline()
        {
            var seed = Encoding.ASCII.GetBytes(@"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce elementum nisi vel magna rhoncus, in aliquam ipsum accumsan. Phasellus efficitur lectus quis malesuada aliquet. Proin mattis sagittis magna vitae blandit. Cras vel diam sagittis, fringilla nunc vitae, vehicula mi. Nullam et auctor mi. Proin vel pharetra tortor. Donec posuere elementum risus, et aliquet magna pharetra non. Curabitur volutpat maximus sem at euismod. Fusce porta, lacus vel varius varius, lacus felis faucibus ante, fermentum sollicitudin elit neque rhoncus tortor. Aenean eget turpis consequat, luctus lorem vehicula, ullamcorper erat.");

            await using var prod = StreamProducer.FromStream(new MemoryStream(seed, false));
            var buffer = new MemoryStream();

            await using var cons = StreamConsumer.Create(async(stream, ctoken) =>
            {
                await stream.CopyToAsync(buffer, 8192, ctoken);
            });
            await prod.ConsumeAsync(cons);

            Assert.True(seed.SequenceEqual(buffer.ToArray()));
        }
Exemple #3
0
        public async Task CancelInsideAsyncProduce()
        {
            using var cancellationTokenSource = new CancellationTokenSource();
            var data     = new byte[128 * 1024];
            var producer = StreamProducer.Create(async(output, _) =>
            {
                while (true)
                {
                    await output.WriteAsync(data.AsMemory(), cancellationTokenSource.Token);
                    await Task.Delay(TimeSpan.FromMilliseconds(10), cancellationTokenSource.Token);
                }
            });
            var consumerCancellationTriggered = false;
            var consumer = StreamConsumer.Create(async(input, cancellationToken) =>
            {
                var buffer = new byte[64 * 1024];
                try
                {
                    while (true)
                    {
                        await input.ReadAsync(buffer.AsMemory(), cancellationToken);
                    }
                }
                catch (OperationCanceledException)
                {
                    consumerCancellationTriggered = true;
                    throw;
                }
            });
            var task = Assert.ThrowsAnyAsync <OperationCanceledException>(() => PipeStreamer.StreamAsync(producer, consumer, CancellationToken.None).AsTask());

            cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(50));
            await task;

            Assert.True(consumerCancellationTriggered);
        }
 public ValueTask PerformAsync(Stream input, Stream output, CancellationToken cancellationToken = default)
 => StreamAsync(
     producer: StreamProducer.Create((output, cancellationToken) => _first.PerformAsync(input, output, cancellationToken)),
     consumer: StreamConsumer.Create((input, cancellationToken) => _second.PerformAsync(input, output, cancellationToken)),
     cancellationToken: cancellationToken
     );
 public ValueTask ProduceAsync(Stream output, CancellationToken cancellationToken = default)
 => StreamAsync(
     producer: _producer,
     consumer: StreamConsumer.Create((input, cancellationToken) => _transformation.PerformAsync(input, output, cancellationToken)),
     cancellationToken: cancellationToken
     );
 public IStreamConsumer CreateConsumer(ContentInfo contentInfo)
 => StreamConsumer.Create(DeserializeAsync).Bind(data => Data = data);