Repository navigation
Multipart pipe reader - #28939
Multipart pipe reader#28939gilmishal wants to merge 8 commits into
Conversation
| } | ||
|
|
||
| [Fact] | ||
| public async Task MultipartPipeReader_TwoPartBodyIncompleteBuffer_OneSectionReadsSuccessfullySecondSectionThrows() |
There was a problem hiding this comment.
I fixed the test to pass, but I am not sure if it's a functional requirement or not - Adding a subsequent AdvanceTo and ReadAsync will throw, but I am not sure if that's what we want.
Basically, it's conflicting with a comment inside the MultipartSectionPipeReader "We want them to consume and advance all of the data before we try to drain the metadata / boundary."
There was a problem hiding this comment.
I think the original scenario here was that both the first and second sections are valid, but the third section is missing. In that case the first two sections would read successfully and it only fails when you try to read the third.
aspnetcore/src/Http/WebUtilities/test/MultipartReaderTests.cs
Lines 285 to 312 in b795ac3
I'd be OK failing sooner for this scenario, it's going to fail eventually anyways, so long as we have a clear reason for the new behavior. Why is the failure mode different than before? It reads the second body and finds the boundary, that should be enough to return the body at that point. Is it hitting a check where it realizes it's reached the end of the pipe without finding the final boundary? I wouldn't have expected that check until the next call to ReadNextSectionAsync.
There was a problem hiding this comment.
Looking at the original now, I am not sure I would say that the behavior had changed.
If we alter the original test and add another read to the section.Body it would fail.
If we alter this test to read the third section instead of continuing to read the rest of the second section it would also fail.
I think that this behavior was changed with my original implementation of the PipeReader, and you returned it to the original behavior, the test just wasn't updated.
Anyways, we might want to consider altering the test to reflect the actual scenario - basically the behavior in both the Stream implementation and the Pipe Implementation is that for an incomplete Section Boundry - the second section will throw before reaching the end - (Pipe - IsCompleted == true, Stream - Read returns 0) - and trying to read the third section will also throw. I would argue that in reality we are more likely to try and read the second section to it's end before attempting to read the third section, especially since we will probably copy each section to it's own Pipe.
| [InlineData(TextAndBoundary, Text, 1)] | ||
| [InlineData(HtmlWithNewLinesAndBoundary, HtmlWithNewLines, 52)] | ||
| [InlineData(TextWithPartialBoundaryMatchAndBoundary, TextWithPartialBoundaryMatch, 14)] | ||
| public async Task MultipartSectionPipeReader_SingleByteReadWithoutAdvance_Success(string input, string expected, int reads) |
There was a problem hiding this comment.
Not sure how it differs from WithAdvance Test. The only difference is that the result isn't buffered and the expected bytes read is larger - both seem like a mistake in the test rather than the functionality, since I am not sure how it's even supposed to pass - I am gonna guess that this is a copy pasted test that was never implemented, but I am double checking.
There was a problem hiding this comment.
The difference is that the prior test always calls AdvanceTo(temp.Buffer.End); but this one calls AdvanceTo(temp.Buffer.Start, temp.Buffer.End);. That makes the former unbuffered and the latter buffered. Both are valid scenarios.
There was a problem hiding this comment.
Oh, I might have missed that. Anyways, I was wondering why they were expecting different number of reads, since they are both pretty similar. I am guessing that this was a mistake.
| var sectionReader = new MultipartSectionPipeReader(pipeReader, new MultipartBoundary(Boundary)); | ||
|
|
||
| var result = await sectionReader.ReadAsync(); | ||
| Assert.False(result.IsCompleted); |
There was a problem hiding this comment.
IsCompleted currently comes out as true, This is because it buffered the entire section on the first Read to the underlying Pipe, and it truly reached the end of the section. I am not sure if that's a problem or not.
There was a problem hiding this comment.
It's fine for IsComplete to return true so long as all of the data is available and we've fully parsed the boundary. Just make sure AdvanceTo(end) also handles advancing the underlying pipe past the parsed boundary.
There was a problem hiding this comment.
Ok then in that case, I think the test is fixed and covers this case.
|
@Tratcher I have made most of the unit tests pass - there are some tests that are still failing, but I need your help deciding what to do with these tests. I feel that the Pipe Implementation itself is solid (not sure about the test coverage though), but we still need to decide how to buffer (and deliver) the sections, to allow reading the sections interchangeably. |
|
Can you post benchmark results here please? Just to see the effect in plain numbers |
Tratcher
left a comment
There was a problem hiding this comment.
I've only skimmed the code and answered questions so far.
| /// <summary> | ||
| /// Gets or sets the body. | ||
| /// </summary> | ||
| public PipeReader BodyReader { get; set; } = default!; |
There was a problem hiding this comment.
One way to buffer the data would be to copy that sections body into a new pipe and assign that reader here. You would need a way to dispose that pipe when you're done with it.
| } | ||
|
|
||
| [Fact] | ||
| public async Task MultipartPipeReader_TwoPartBodyIncompleteBuffer_OneSectionReadsSuccessfullySecondSectionThrows() |
There was a problem hiding this comment.
I think the original scenario here was that both the first and second sections are valid, but the third section is missing. In that case the first two sections would read successfully and it only fails when you try to read the third.
aspnetcore/src/Http/WebUtilities/test/MultipartReaderTests.cs
Lines 285 to 312 in b795ac3
I'd be OK failing sooner for this scenario, it's going to fail eventually anyways, so long as we have a clear reason for the new behavior. Why is the failure mode different than before? It reads the second body and finds the boundary, that should be enough to return the body at that point. Is it hitting a check where it realizes it's reached the end of the pipe without finding the final boundary? I wouldn't have expected that check until the next call to ReadNextSectionAsync.
| [InlineData(TextAndBoundary, Text, 1)] | ||
| [InlineData(HtmlWithNewLinesAndBoundary, HtmlWithNewLines, 52)] | ||
| [InlineData(TextWithPartialBoundaryMatchAndBoundary, TextWithPartialBoundaryMatch, 14)] | ||
| public async Task MultipartSectionPipeReader_SingleByteReadWithoutAdvance_Success(string input, string expected, int reads) |
There was a problem hiding this comment.
The difference is that the prior test always calls AdvanceTo(temp.Buffer.End); but this one calls AdvanceTo(temp.Buffer.Start, temp.Buffer.End);. That makes the former unbuffered and the latter buffered. Both are valid scenarios.
| var sectionReader = new MultipartSectionPipeReader(pipeReader, new MultipartBoundary(Boundary)); | ||
|
|
||
| var result = await sectionReader.ReadAsync(); | ||
| Assert.False(result.IsCompleted); |
There was a problem hiding this comment.
It's fine for IsComplete to return true so long as all of the data is available and we've fully parsed the boundary. Just make sure AdvanceTo(end) also handles advancing the underlying pipe past the parsed boundary.
I am unable to run any of the benchmarking projects - I am getting this error I am not sure what's causing it, and I couldn't find any relevant documentation in this repo, or on BenchmarkDotNet. I can say that I did run activate.ps1 assuming it was related to the cli dotnet version being used (apperantly not though) - but I do think it might be related to this lines in Program.cs (in the performance projects) I don't have any other angle at the moment, other than perhaps trying to build this thing for .net 5. |
|
@Tratcher I have addressed your comments and fixed the tests accordingly, please verify that you approve my changes, and with your permission I will fix TryRead and create the tests for it. |
39cb01c to
9f90bf6
Compare
|
👀 |
Tratcher
left a comment
There was a problem hiding this comment.
Here's a little more detailed feedback. I didn't get to the most complex part in MultipartSectionPipeReader.
I talked this over with our team and we reached two conclusions:
- We're starting our 6.0 development and focusing on P0 features for the first milestone or two. We do think this multipart pipe reader is important for 6.0, but it will be a milestone or two before we're able to focus on it.
- @jkotalik has a lot more experience with custom pipe readers so he'll take over reviewing this PR.
| if (headersLength > HeadersLengthLimit) | ||
| { | ||
| throw new InvalidDataException($"Multipart headers length limit {HeadersLengthLimit} exceeded."); | ||
| } |
There was a problem hiding this comment.
Why is this check needed? It looks like TryParseHeadersToEnd is actively checking the limit as it parsers. Checking after parsing completed is too late regardless.
There was a problem hiding this comment.
yes, it's redundant I'll remove.
| } | ||
| finally | ||
| { | ||
| _pipeReader.AdvanceTo(buffer.Start, buffer.End); |
There was a problem hiding this comment.
I suspect buffer.End isn't always the right value here. I think these are the scenarios:
A) Say we finished parsing the headers, but there was body data still in the buffer. That wasn't observed data. Both AdvanceTo parameters should point at the end of the headers and no further. Should TryParseHeadersToEnd slice the buffer accordingly?
B) We didn't reach the endo the headers, in which case buffer.End is the right value.
C) An exception was thrown. Then it probably doesn't matter what the value is passed here, so long as it doesn't ever go backwards.
There was a problem hiding this comment.
the buffer is being sliced within TryParseHeadersToEnd
There was a problem hiding this comment.
I still think there could be issues here. I think the code path for TryParseHeaderstoEndFast is fine, but I have concerns about TryParseheadersToEndSlow. At the end, you are doing buffer = default, which I think needs to be buffer = buffer.Slice(sequenceReader.Position);
There was a problem hiding this comment.
I think you are right. This certainly seems like a possible issue, I will also add a test for coverage.
There was a problem hiding this comment.
Definitely an issue, I managed to reproduce it when removing the ParseHeadersFast method and using a SingleByteStream - there were duplicate header values - updated the test as much as I could.
I do suggest adding tests forcing ParseHeadersSlow - but I am not sure how to do it, I don't know how to force multi segment - and I wouldn't want to change functionalities just for the test. Anyways the issue itself is fixed by your suggestion.
addressed todo regarding HeadersLengthLimit Co-authored-by: Chris Ross <[email protected]>
Co-authored-by: Chris Ross <[email protected]>
jkotalik
left a comment
There was a problem hiding this comment.
Some initial comments. Still trying to get my head around the MultipartSectionPipeReader.
|
|
||
| if (_currentSectionReader.FinalBoundaryFound) | ||
| { | ||
| return null; |
There was a problem hiding this comment.
In the original MultipartReader, I see the extra call to DrainAsync on the stream:
if (_currentStream.FinalBoundaryFound)
{
// There may be trailer data after the last boundary.
await _stream.DrainAsync(HeadersLengthLimit, cancellationToken);
return null;
}Wouldn't the same apply here?
There was a problem hiding this comment.
In the pipeReader implementation we are reading to the end of the pipeReader once we find the finalBoundary, so in practice the behavior is the same, and there is no need to drain the trailing data - basically the difference is that the pipe is just drained to end as soon as the final boundary is found , instead of waiting for a subsequent DrainAsync.
aspnetcore/src/Http/WebUtilities/src/MultipartSectionPipeReader.cs
Lines 187 to 195 in b784d8e
|
|
||
| // We need to create a Span from a ReadOnlySpan. This cast is safe because the memory is still held by the pipe | ||
| // We will also create a string from it by the end of the function. | ||
| var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(readOnlySpan[0]), readOnlySpan.Length); |
There was a problem hiding this comment.
I'm not a fan of this, the only reason for unsafe here is to call Trim for spaces?
Part of me wonders if it wouldn't be hard to implement a method that does this by checking the front and back of the read only span and moving the start and end indices.
There was a problem hiding this comment.
May we could microbenchmark this to make sure it's performant.
| { | ||
| var didFinishParsing = TryParseHeadersToEndFast(buffer.First.Span, | ||
| ref accumulator, | ||
| HeadersLengthLimit - headersLength, |
There was a problem hiding this comment.
Pass in headersLength here instead to make the calculations for exceptions easier.
| HeadersLengthLimit - headersLength, | |
| headersLength, |
| // Don't buffer indefinitely | ||
| if (headersLength + sequenceReader.Consumed > HeadersLengthLimit) | ||
| { | ||
| throw new InvalidDataException($"Line length limit {HeadersLengthLimit - headersLength} exceeded."); |
There was a problem hiding this comment.
| throw new InvalidDataException($"Line length limit {HeadersLengthLimit - headersLength} exceeded."); | |
| throw new InvalidDataException($"Multipart headers length limit {HeadersLengthLimit} exceeded."); |
| } | ||
| finally | ||
| { | ||
| _pipeReader.AdvanceTo(buffer.Start, buffer.End); |
There was a problem hiding this comment.
I still think there could be issues here. I think the code path for TryParseHeaderstoEndFast is fine, but I have concerns about TryParseheadersToEndSlow. At the end, you are doing buffer = default, which I think needs to be buffer = buffer.Slice(sequenceReader.Position);
| if (_currentSectionReader == null) // first call. | ||
| { | ||
| // This section will drain any preamble data and remove the first boundary marker. | ||
| _currentSectionReader = new MultipartSectionPipeReader(_pipeReader, _boundary) { LengthLimit = HeadersLengthLimit }; |
There was a problem hiding this comment.
Idea (for future), could we get away with not having the MultipartSectionPipeReader class at all, tracking state in the MultipartPipeReader?
|
@jkotalik any more comments? Can I continue to the next steps? |
|
@gilmishal apologies, I'll get back to this within the week. |
| namespace Microsoft.AspNetCore.WebUtilities | ||
| { | ||
| /// <summary> | ||
| /// a Pipe Implementation of a Http Multipart Section |
There was a problem hiding this comment.
| /// a Pipe Implementation of a Http Multipart Section | |
| /// A Pipe Implementation of a Http Multipart Section |
| { | ||
| internal class MultipartSectionPipeReader : PipeReader | ||
| { | ||
| private static ReadOnlySpan<byte> CrlfDelimiter => new byte[] { (byte)'\r', (byte)'\n' }; |
There was a problem hiding this comment.
See https://github.com/dotnet/aspnetcore/blob/main/src/Servers/Kestrel/Core/src/Internal/Http/Http1ContentLengthMessageBody.cs for reference to another custom PipeReader implemented (doesn't directly implement PipeReader, but has the same methods).
jkotalik
left a comment
There was a problem hiding this comment.
It's hard to follow what's going on in ReadAsync/TryRead/AdvanceTo. One thing I found is writing an example in code with a boundary and end-of-section to show how each of the cases are covered helps with understanding.
| if (isFinalBlock && _unconsumedData.Length < _boundary.FinalBoundaryLength) | ||
| { | ||
| _pipeReader.AdvanceTo(_unconsumedData.End); | ||
| throw new IOException("Unexpected end of Stream, the content may have already been read by another component. "); |
There was a problem hiding this comment.
| throw new IOException("Unexpected end of Stream, the content may have already been read by another component. "); | |
| throw new IOException("Unexpected end of Stream, the content may have already been read by another component."); |
| /// <summary> | ||
| /// Pipe implementation of a reader for HTTP Multipart Content Type | ||
| /// </summary> | ||
| public class MultipartPipeReader |
There was a problem hiding this comment.
Can we make these internal for now until we enable the MultipartPipeReader by default? I'd rather us not forget to make them internal/private if we don't make it the default in the future.
| if (!_boundaryFound) | ||
| { | ||
| // We must be examining a partial boundary match, keep reading. | ||
| _pipeReader.AdvanceTo(readResult.Buffer.Start, _unconsumedData.End); |
There was a problem hiding this comment.
I don't see how this could ever be hit. As long as we are updating the pipe correctly, wouldn't _bodyBuffer.Length always be greater than priorDataLength?
| throw new InvalidOperationException("AdvanceTo was not called after the last read operation."); | ||
| } | ||
|
|
||
| // TODO: Refactor. |
There was a problem hiding this comment.
I think this still needs to be refactored; it was very hard to follow what was going on.
My gut says that ReadAsync and TryRead should be very similar, but these methods are different in structure. From a readability perspective, having these match as closely as possible would help.
| else | ||
| { | ||
| // We reached the end of the section, we should advance to the end. | ||
| _pipeReader.AdvanceTo(_unconsumedData.End); |
There was a problem hiding this comment.
If the data is unconsumed, shouldn't we still examine the rest of the unconsumed data even if we found a boundary?
|
@gilmishal you get the chance to respond to this feedback? |
Been a crazy month. I'll respond tomorrow. |
|
I'm going to close this for now, feel free to reopen when you have the chance to review and respond to feedback. |
Continuing work on MultipartForm PipeReader Implementation from PR #15056.
Addresses #11377