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

Ensure PipeWriter is flushed #485

Merged
merged 3 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@ bool IHttpResponseBufferingFeature.IsEnabled

private async ValueTask FlushInternalAsync()
{
if (_pipeWriter is { })
{
await _pipeWriter.FlushAsync();
}

if (_state is StreamState.Buffering && _bufferedStream is not null && !SuppressContent)
{
if (_filter is { } filter)
Expand All @@ -111,7 +116,23 @@ private async ValueTask FlushInternalAsync()

Stream IHttpResponseBodyFeature.Stream => this;

PipeWriter IHttpResponseBodyFeature.Writer => _pipeWriter ??= PipeWriter.Create(this, new StreamPipeWriterOptions(leaveOpen: true));
PipeWriter IHttpResponseBodyFeature.Writer
{
get
{
if (_pipeWriter is null)
{
_pipeWriter = PipeWriter.Create(this, new StreamPipeWriterOptions(leaveOpen: true));

if (_state is StreamState.Complete)
{
_pipeWriter.Complete();
}
}

return _pipeWriter;
}
}

public bool SuppressContent
{
Expand Down Expand Up @@ -229,6 +250,11 @@ private async Task CompleteAsync()

_state = StreamState.Complete;

if (_pipeWriter is { })
{
await _pipeWriter.CompleteAsync();
}

await _responseBodyFeature.CompleteAsync();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
Expand Down Expand Up @@ -42,6 +43,32 @@ public async Task BufferedOutputIsFlushed()
Assert.Equal(ContentValue, result);
}

[Fact]
public async Task OutputPipeIsFlushed()
{
const string Message = "hello world from pipe!";

var result = await RunAsync(context =>
{
context.AsAspNetCore().Response.BodyWriter.Write(Encoding.UTF8.GetBytes(Message));
});

Assert.Equal(Message, result);
}

[Fact]
public async Task OutputPipeIsMarkedCompleteIfRequestIsComplete()
{
var result = await RunAsync(async context =>
{
await context.AsAspNetCore().Response.CompleteAsync();

Assert.Throws<InvalidOperationException>(() => context.AsAspNetCore().Response.BodyWriter.Write("Hello world"u8));
});

Assert.Empty(result);
}

[Fact]
public async Task BufferedOutputIsFlushedOnceWithStart()
{
Expand Down