-
Notifications
You must be signed in to change notification settings - Fork 25.3k
Refactor gcp-fixture multipart parser #125828
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
2fb738d
refactor gcp-fixture multipart parser
mhl-b 28d4481
remove ring-buffer
mhl-b 4ef1236
naming
mhl-b 5105d4c
Merge remote-tracking branch 'upstream/main' into gcp-fixture-multipa…
mhl-b 0dfddd6
add tests
mhl-b 1008194
Merge branch 'main' into gcp-fixture-multipart-refactor
mhl-b 771e069
Merge remote-tracking branch 'upstream/main' into gcp-fixture-multipa…
mhl-b 4eb8b23
merge main
mhl-b 3381864
generic multipart parser
mhl-b f8eb315
Merge branch 'gcp-fixture-multipart-refactor' of github.com:mhl-b/ela…
mhl-b f3210e4
[CI] Auto commit changes from spotless
elasticsearchmachine 9714b32
exceptions
mhl-b 019a04f
Merge branch 'gcp-fixture-multipart-refactor' of github.com:mhl-b/ela…
mhl-b b4869f5
test zero-sized blob
mhl-b 47912f5
sanitize content
mhl-b 8de1110
Merge branch 'main' into gcp-fixture-multipart-refactor
mhl-b 1505b48
Merge remote-tracking branch 'upstream/main' into gcp-fixture-multipa…
mhl-b b7ef093
Merge branch 'gcp-fixture-multipart-refactor' of github.com:mhl-b/ela…
mhl-b 905620d
random multipart boundary
mhl-b efda0e7
cleanup
mhl-b 797d27d
Merge branch 'main' into gcp-fixture-multipart-refactor
mhl-b File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
refactor gcp-fixture multipart parser
- Loading branch information
commit 2fb738dad3ac3c0dfd4a26c2d6b5ed9187093331
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
177 changes: 177 additions & 0 deletions
177
test/fixtures/gcs-fixture/src/main/java/fixture/gcs/MultipartUpload.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,177 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the "Elastic License | ||
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side | ||
* Public License v 1"; you may not use this file except in compliance with, at | ||
* your election, the "Elastic License 2.0", the "GNU Affero General Public | ||
* License v3.0 only", or the "Server Side Public License, v 1". | ||
*/ | ||
|
||
package fixture.gcs; | ||
|
||
import com.sun.net.httpserver.HttpExchange; | ||
|
||
import org.elasticsearch.common.bytes.BytesArray; | ||
import org.elasticsearch.common.bytes.BytesReference; | ||
import org.elasticsearch.common.bytes.CompositeBytesReference; | ||
|
||
import java.io.ByteArrayOutputStream; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.regex.Pattern; | ||
import java.util.zip.GZIPInputStream; | ||
|
||
record MultipartUpload(String bucket, String name, String generation, String crc32, String md5, BytesReference content) { | ||
|
||
static final byte[] CRLFCRLF = new byte[] { '\r', '\n', '\r', '\n' }; | ||
static final Pattern METADATA_PATTERN = Pattern.compile("\"(bucket|name|generation|crc32c|md5Hash)\":\"([^\"]*)\""); | ||
static final Pattern BOUNDARY_HEADER_PATTERN = Pattern.compile("multipart/\\w+; boundary=\\\"?(.*)\\\"?"); | ||
|
||
/** | ||
* Reads HTTP content of MultipartUpload. First part is always json metadata, followed by binary parts. | ||
* Every part has own headers and content. Parts are separated by dash-boundary(--boundary) delimiter, | ||
* and boundary is defined in the HTTP header Content-Type, | ||
* like this {@code multipart/related; boundary=__END_OF_PART__4914cd49-4065-44f6-9846-ce805fe1e77f__}. | ||
* Last part, close-delimiter, is dashed from both sides {@code --boundary--}. | ||
* Part headers are separated from the body by double CRLF. | ||
* | ||
* More details here <a href=https://www.rfc-editor.org/rfc/rfc2046.html#page-19>rfc2046</a>. | ||
* | ||
* <pre> | ||
* {@code | ||
* --boundary CRLF | ||
* headers CRLF | ||
* CRLF | ||
* content CRLF | ||
* --boundary CRLF | ||
* headers CRLF | ||
* CRLF | ||
* content CRLF | ||
* --boundary-- | ||
* } | ||
* </pre> | ||
*/ | ||
static MultipartUpload parseBody(HttpExchange exchange, InputStream gzipInput) throws IOException { | ||
var boundary = getBoundaryHeader(exchange); | ||
try (var input = new GZIPInputStream(gzipInput)) { | ||
var dashBoundary = ("--" + boundary).getBytes(); | ||
var bodyPartDelimiter = ("\r\n--" + boundary).getBytes(); | ||
|
||
// https://www.rfc-editor.org/rfc/rfc2046.html#page-22 | ||
// multipart-body := [preamble CRLF] | ||
// dash-boundary transport-padding CRLF | ||
// body-part *encapsulation | ||
// close-delimiter transport-padding | ||
// [CRLF epilogue] | ||
// | ||
// there is no transport-padding and epilogue in our case | ||
skipDashBoundary(input, dashBoundary); | ||
|
||
// read first body-part - blob metadata json | ||
readByDelimiter(input, CRLFCRLF); // ignore body-part headers | ||
var metadataBytes = readByDelimiter(input, bodyPartDelimiter); | ||
var match = METADATA_PATTERN.matcher(metadataBytes.utf8ToString()); | ||
String bucket = "", name = "", gen = "", crc = "", md5 = ""; | ||
while (match.find()) { | ||
switch (match.group(1)) { | ||
case "bucket" -> bucket = match.group(2); | ||
case "name" -> name = match.group(2); | ||
case "generation" -> gen = match.group(2); | ||
case "crc32c" -> crc = match.group(2); | ||
case "md5Hash" -> md5 = match.group(2); | ||
} | ||
} | ||
var blobParts = new ArrayList<BytesReference>(); | ||
|
||
// read content from remaining parts, can be 0..n | ||
while (readCloseDelimiterOrCRLF(input) == false) { | ||
readByDelimiter(input, CRLFCRLF); // ignore headers | ||
var content = readByDelimiter(input, bodyPartDelimiter); | ||
blobParts.add(content); | ||
} | ||
|
||
var compositeBuf = CompositeBytesReference.of(blobParts.toArray(new BytesReference[0])); | ||
return new MultipartUpload(bucket, name, gen, crc, md5, compositeBuf); | ||
} | ||
} | ||
|
||
static String getBoundaryHeader(HttpExchange exchange) { | ||
var m = BOUNDARY_HEADER_PATTERN.matcher(exchange.getRequestHeaders().getFirst("Content-Type")); | ||
if (m.matches() == false) { | ||
throw new IllegalArgumentException("boundary header is not present"); | ||
} | ||
return m.group(1); | ||
} | ||
|
||
/** | ||
* read and discard very first delimiter | ||
*/ | ||
static void skipDashBoundary(InputStream is, byte[] dashBoundary) throws IOException { | ||
var b = is.readNBytes(dashBoundary.length); | ||
if (Arrays.equals(b, dashBoundary) == false) { | ||
throw new IllegalStateException( | ||
"cannot read dash-boundary, expect=" + Arrays.toString(dashBoundary) + " got=" + Arrays.toString(b) | ||
); | ||
} | ||
skipCRLF(is); | ||
} | ||
|
||
static void skipCRLF(InputStream is) throws IOException { | ||
var cr = is.read(); | ||
var lf = is.read(); | ||
if (cr != '\r' && lf != '\n') { | ||
throw new IllegalStateException("cannot read CRLF got " + cr + " " + lf); | ||
} | ||
} | ||
|
||
/** | ||
* Must call after reading body-part-delimiter to see if there are more parts. | ||
* If there are no parts, a closing double dash is expected, otherwise CRLF. | ||
*/ | ||
static boolean readCloseDelimiterOrCRLF(InputStream is) throws IOException { | ||
var d1 = is.read(); | ||
var d2 = is.read(); | ||
if (d1 == '-' && d2 == '-') { | ||
return true; | ||
} else if (d1 == '\r' && d2 == '\n') { | ||
return false; | ||
} else { | ||
throw new IllegalStateException("expect '--' or CRLF, got " + d1 + " " + d2); | ||
} | ||
} | ||
|
||
/** | ||
* Read bytes from stream into buffer until reach given delimiter. The delimiter is consumed too. | ||
*/ | ||
static BytesReference readByDelimiter(InputStream is, byte[] delimiter) throws IOException { | ||
mhl-b marked this conversation as resolved.
Show resolved
Hide resolved
|
||
var out = new ByteArrayOutputStream(1024); | ||
var delimiterCheckRing = new byte[delimiter.length]; // a ring-buffer that tracks last N bytes | ||
mhl-b marked this conversation as resolved.
Show resolved
Hide resolved
|
||
var ringOffset = 0; | ||
while (true) { | ||
var c = is.read(); | ||
if (c == -1) { | ||
throw new IllegalStateException("expected delimiter, but reached end of stream "); | ||
} | ||
var b = (byte) c; | ||
delimiterCheckRing[ringOffset] = b; | ||
out.write(b); | ||
ringOffset = (ringOffset + 1) % delimiter.length; | ||
if (c == delimiter[delimiter.length - 1]) { // try to compare ring buffer with delimiter when last char matches | ||
var isMatch = true; | ||
for (int i = 0; i < delimiter.length; i++) { | ||
var ri = (i + ringOffset) % delimiter.length; | ||
if (delimiterCheckRing[ri] != delimiter[i]) { | ||
isMatch = false; | ||
break; | ||
} | ||
} | ||
if (isMatch) { | ||
var bytes = out.toByteArray(); | ||
return new BytesArray(bytes, 0, bytes.length - delimiter.length); | ||
} | ||
} | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would like to keep the behaviour where an invalid body causes a test failure rather than just an
IllegalStateException
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Throw AssertionError errors from the MultipartUpload.parseBody now.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was sort of hoping to see tests that ensured that this kind of malformed body would throw an IAE from the parser. Throwing
AssertionError
from the parser itself basically means you can only test the happy path (or else catchAssertionError
in tests which is best avoided if possible).