Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ReadAtLeastAsync implementation for StreamPipeReader #52246

Merged
merged 14 commits into from
May 10, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -189,152 +189,168 @@ public override void Complete(Exception? exception = null)
}

/// <inheritdoc />
public override async ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
{
// TODO ReadyAsync needs to throw if there are overlapping reads.
ThrowIfCompleted();

cancellationToken.ThrowIfCancellationRequested();

// PERF: store InternalTokenSource locally to avoid querying it twice (which acquires a lock)
CancellationTokenSource tokenSource = InternalTokenSource;
if (TryReadInternal(tokenSource, out ReadResult readResult))
{
return readResult;
return new ValueTask<ReadResult>(readResult);
}

if (_isStreamCompleted)
{
return new ReadResult(buffer: default, isCanceled: false, isCompleted: true);
ReadResult completedResult = new ReadResult(buffer: default, isCanceled: false, isCompleted: true);
return new ValueTask<ReadResult>(completedResult);
}

CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeReader)state!).Cancel(), this);
}
return Core(tokenSource, cancellationToken);

using (reg)
async ValueTask<ReadResult> Core(CancellationTokenSource tokenSource, CancellationToken cancellationToken)
davidfowl marked this conversation as resolved.
Show resolved Hide resolved
{
var isCanceled = false;
try
CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
// This optimization only makes sense if we don't have anything buffered
if (UseZeroByteReads && _bufferedBytes == 0)
{
// Wait for data by doing 0 byte read before
await InnerStream.ReadAsync(Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(false);
}
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeReader)state!).Cancel(), this);
}

AllocateReadTail();
using (reg)
{
var isCanceled = false;
try
{
// This optimization only makes sense if we don't have anything buffered
if (UseZeroByteReads && _bufferedBytes == 0)
{
// Wait for data by doing 0 byte read before
await InnerStream.ReadAsync(Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(false);
}

Memory<byte> buffer = _readTail!.AvailableMemory.Slice(_readTail.End);
AllocateReadTail();

int length = await InnerStream.ReadAsync(buffer, tokenSource.Token).ConfigureAwait(false);
Memory<byte> buffer = _readTail!.AvailableMemory.Slice(_readTail.End);

Debug.Assert(length + _readTail.End <= _readTail.AvailableMemory.Length);
int length = await InnerStream.ReadAsync(buffer, tokenSource.Token).ConfigureAwait(false);

_readTail.End += length;
_bufferedBytes += length;
Debug.Assert(length + _readTail.End <= _readTail.AvailableMemory.Length);

if (length == 0)
{
_isStreamCompleted = true;
}
}
catch (OperationCanceledException)
{
ClearCancellationToken();
_readTail.End += length;
_bufferedBytes += length;

if (tokenSource.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// Catch cancellation and translate it into setting isCanceled = true
isCanceled = true;
if (length == 0)
{
_isStreamCompleted = true;
}
}
else
catch (OperationCanceledException)
{
throw;
ClearCancellationToken();

if (tokenSource.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// Catch cancellation and translate it into setting isCanceled = true
isCanceled = true;
}
else
{
throw;
}

}

return new ReadResult(GetCurrentReadOnlySequence(), isCanceled, _isStreamCompleted);
}

return new ReadResult(GetCurrentReadOnlySequence(), isCanceled, _isStreamCompleted);
}
}

protected override async ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
{
// TODO ReadyAsync needs to throw if there are overlapping reads.
ThrowIfCompleted();

cancellationToken.ThrowIfCancellationRequested();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should really be:

if (cancellationToken.IsCancellationRequested)
{
    return ValueTask.FromCanceled<ReadResult>(cancellationToken);
}

or to be able to target downlevel as well:

if (cancellationToken.IsCancellationRequested)
{
    return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(cancellationToken));
}

Otherwise, this is going to propagate the OperationCanceledException synchronously out of the ReadAtLeastAsync call, when we generally prefer to propagate it as part of the returned task.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@manandre would you like to take this one?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure!
Fix proposal available in PR #53306


// PERF: store InternalTokenSource locally to avoid querying it twice (which acquires a lock)
CancellationTokenSource tokenSource = InternalTokenSource;
if (TryReadInternal(tokenSource, out ReadResult readResult))
{
if (readResult.Buffer.Length >= minimumSize || readResult.IsCompleted || readResult.IsCanceled)
{
return readResult;
return new ValueTask<ReadResult>(readResult);
}
}

if (_isStreamCompleted)
{
return new ReadResult(buffer: default, isCanceled: false, isCompleted: true);
ReadResult completedResult = new ReadResult(buffer: default, isCanceled: false, isCompleted: true);
return new ValueTask<ReadResult>(completedResult);
}

CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeReader)state!).Cancel(), this);
}
return Core(minimumSize, tokenSource, cancellationToken);

using (reg)
async ValueTask<ReadResult> Core(int minimumSize, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
{
var isCanceled = false;
try
CancellationTokenRegistration reg = default;
if (cancellationToken.CanBeCanceled)
{
// This optimization only makes sense if we don't have anything buffered
if (UseZeroByteReads && _bufferedBytes == 0)
{
// Wait for data by doing 0 byte read before
await InnerStream.ReadAsync(Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(false);
}
reg = cancellationToken.UnsafeRegister(state => ((StreamPipeReader)state!).Cancel(), this);
}

while (_bufferedBytes < minimumSize)
using (reg)
{
var isCanceled = false;
try
{
AllocateReadTail(minimumSize);
// This optimization only makes sense if we don't have anything buffered
if (UseZeroByteReads && _bufferedBytes == 0)
manandre marked this conversation as resolved.
Show resolved Hide resolved
{
// Wait for data by doing 0 byte read before
await InnerStream.ReadAsync(Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(false);
}

Memory<byte> buffer = _readTail!.AvailableMemory.Slice(_readTail.End);
do
{
AllocateReadTail(minimumSize);

int length = await InnerStream.ReadAsync(buffer, tokenSource.Token).ConfigureAwait(false);
Memory<byte> buffer = _readTail!.AvailableMemory.Slice(_readTail.End);

Debug.Assert(length + _readTail.End <= _readTail.AvailableMemory.Length);
int length = await InnerStream.ReadAsync(buffer, tokenSource.Token).ConfigureAwait(false);

_readTail.End += length;
_bufferedBytes += length;
Debug.Assert(length + _readTail.End <= _readTail.AvailableMemory.Length);

if (length == 0)
{
_isStreamCompleted = true;
break;
}
}
}
catch (OperationCanceledException)
{
ClearCancellationToken();
_readTail.End += length;
_bufferedBytes += length;

if (tokenSource.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// Catch cancellation and translate it into setting isCanceled = true
isCanceled = true;
if (length == 0)
{
_isStreamCompleted = true;
break;
}
} while (_bufferedBytes < minimumSize);
}
else
catch (OperationCanceledException)
{
throw;
ClearCancellationToken();

if (tokenSource.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// Catch cancellation and translate it into setting isCanceled = true
isCanceled = true;
}
else
{
throw;
}

}

return new ReadResult(GetCurrentReadOnlySequence(), isCanceled, _isStreamCompleted);
}

return new ReadResult(GetCurrentReadOnlySequence(), isCanceled, _isStreamCompleted);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace System.IO.Pipelines.Tests
{
public class BasePipeReaderReadAtLeastAsyncTests : ReadAtLeastAsyncTests
{
private PipeReader? _pipeReader;
protected override PipeReader PipeReader => _pipeReader ?? (_pipeReader = new BasePipeReader(Pipe.Reader));
}
}
Loading