Skip to content

Add more tests with ByteArrayAsyncRequestBody #4214

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 1 commit into from
Jul 19, 2023
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 @@ -20,15 +20,21 @@

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
Expand All @@ -51,11 +57,12 @@ public class SplittingPublisherTest {

private static final int NUM_OF_CHUNK = (int) Math.ceil(CONTENT_SIZE / (double) CHUNK_SIZE);

private static RandomTempFile testFile;
private static File testFile;

@BeforeAll
public static void beforeAll() throws IOException {
testFile = new RandomTempFile("testfile.dat", CONTENT_SIZE);
testFile = File.createTempFile("SplittingPublisherTest", UUID.randomUUID().toString());
Files.write(testFile.toPath(), CONTENT);
}

@AfterAll
Expand All @@ -65,46 +72,19 @@ public static void afterAll() throws Exception {

@ParameterizedTest
@ValueSource(ints = {CHUNK_SIZE, CHUNK_SIZE * 2 - 1, CHUNK_SIZE * 2})
void differentChunkSize_shouldSplitAsyncRequestBodyCorrectly(int upstreamByteBufferSize) throws Exception {
CompletableFuture<Void> future = new CompletableFuture<>();
SplittingPublisher splittingPublisher = SplittingPublisher.builder()
.resultFuture(future)
.asyncRequestBody(FileAsyncRequestBody.builder()
.path(testFile.toPath())
.chunkSizeInBytes(upstreamByteBufferSize)
.build())

.resultFuture(future)
.chunkSizeInBytes((long) CHUNK_SIZE)
.maxMemoryUsageInBytes((long) CHUNK_SIZE * 4)
.build();

List<CompletableFuture<byte[]>> futures = new ArrayList<>();
void differentChunkSize_shouldSplitAsyncRequestBodyCorrectly(int chunkSize) throws Exception {

splittingPublisher.subscribe(requestBody -> {
CompletableFuture<byte[]> baosFuture = new CompletableFuture<>();
BaosSubscriber subscriber = new BaosSubscriber(baosFuture);
futures.add(baosFuture);
requestBody.subscribe(subscriber);
}).get(5, TimeUnit.SECONDS);

assertThat(futures.size()).isEqualTo(NUM_OF_CHUNK);
FileAsyncRequestBody fileAsyncRequestBody = FileAsyncRequestBody.builder()
.path(testFile.toPath())
.chunkSizeInBytes(chunkSize)
.build();
verifySplitContent(fileAsyncRequestBody, chunkSize);
}

for (int i = 0; i < futures.size(); i++) {
try (FileInputStream fileInputStream = new FileInputStream(testFile)) {
byte[] expected;
if (i == futures.size() - 1) {
expected = new byte[1];
} else {
expected = new byte[5];
}
fileInputStream.skip(i * 5);
fileInputStream.read(expected);
byte[] actualBytes = futures.get(i).join();
assertThat(actualBytes).isEqualTo(expected);
};
}
assertThat(future).isCompleted();
@ParameterizedTest
@ValueSource(ints = {CHUNK_SIZE, CHUNK_SIZE * 2 - 1, CHUNK_SIZE * 2})
void differentChunkSize_byteArrayShouldSplitAsyncRequestBodyCorrectly(int chunkSize) throws Exception {
verifySplitContent(AsyncRequestBody.fromBytes(CONTENT), chunkSize);
}


Expand All @@ -115,7 +95,7 @@ void cancelFuture_shouldCancelUpstream() throws IOException {
SplittingPublisher splittingPublisher = SplittingPublisher.builder()
.resultFuture(future)
.asyncRequestBody(asyncRequestBody)
.chunkSizeInBytes((long) CHUNK_SIZE)
.chunkSizeInBytes(CHUNK_SIZE)
.maxMemoryUsageInBytes(10L)
.build();

Expand All @@ -139,7 +119,7 @@ public Optional<Long> contentLength() {
SplittingPublisher splittingPublisher = SplittingPublisher.builder()
.resultFuture(future)
.asyncRequestBody(asyncRequestBody)
.chunkSizeInBytes((long) CHUNK_SIZE)
.chunkSizeInBytes(CHUNK_SIZE)
.maxMemoryUsageInBytes(10L)
.build();

Expand Down Expand Up @@ -177,6 +157,46 @@ public Optional<Long> contentLength() {

}


private static void verifySplitContent(AsyncRequestBody asyncRequestBody, int chunkSize) throws Exception {
CompletableFuture<Void> future = new CompletableFuture<>();
SplittingPublisher splittingPublisher = SplittingPublisher.builder()
.resultFuture(future)
.asyncRequestBody(asyncRequestBody)
.resultFuture(future)
.chunkSizeInBytes(chunkSize)
.maxMemoryUsageInBytes((long) chunkSize * 4)
.build();

List<CompletableFuture<byte[]>> futures = new ArrayList<>();

splittingPublisher.subscribe(requestBody -> {
CompletableFuture<byte[]> baosFuture = new CompletableFuture<>();
BaosSubscriber subscriber = new BaosSubscriber(baosFuture);
futures.add(baosFuture);
requestBody.subscribe(subscriber);
}).get(5, TimeUnit.SECONDS);

assertThat(futures.size()).isEqualTo((int) Math.ceil(CONTENT_SIZE / (double) chunkSize));

for (int i = 0; i < futures.size(); i++) {
try (FileInputStream fileInputStream = new FileInputStream(testFile)) {
byte[] expected;
if (i == futures.size() - 1) {
int lastChunk = CONTENT_SIZE % chunkSize == 0 ? chunkSize : (CONTENT_SIZE % chunkSize);
expected = new byte[lastChunk];
} else {
expected = new byte[chunkSize];
}
fileInputStream.skip(i * chunkSize);
fileInputStream.read(expected);
byte[] actualBytes = futures.get(i).join();
assertThat(actualBytes).isEqualTo(expected);
};
}
assertThat(future).isCompleted();
}

private static class TestAsyncRequestBody implements AsyncRequestBody {
private volatile boolean cancelled;
private volatile boolean isDone;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.crt.S3CrtClientCopyIntegrationTest.randomBytes;
import static software.amazon.awssdk.services.s3.multipart.S3ClientMultiPartCopyIntegrationTest.randomBytes;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.computeCheckSum;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,12 @@ void copy_ssecServerSideEncryption_shouldSucceed(S3AsyncClient s3AsyncClient) {
String newB64Key = Base64.getEncoder().encodeToString(newSecretKey);
String newB64KeyMd5 = Md5Utils.md5AsBase64(newSecretKey);

// MPU S3 client gets stuck
// TODO: change back to s3AsyncClient once the issue is fixed in MPU S3 client
s3Async.putObject(r -> r.bucket(BUCKET)
.key(ORIGINAL_OBJ)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5),
AsyncRequestBody.fromBytes(originalContent)).join();
s3AsyncClient.putObject(r -> r.bucket(BUCKET)
.key(ORIGINAL_OBJ)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5),
AsyncRequestBody.fromBytes(originalContent)).join();

CompletableFuture<CopyObjectResponse> future = s3AsyncClient.copyObject(c -> c
.sourceBucket(BUCKET)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.commons.lang3.RandomStringUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
Expand All @@ -42,15 +48,18 @@ public class S3MultipartClientPutObjectIntegrationTest extends S3IntegrationTest
private static final String TEST_KEY = "testfile.dat";
private static final int OBJ_SIZE = 19 * 1024 * 1024;

private static RandomTempFile testFile;
private static File testFile;
private static S3AsyncClient mpuS3Client;

@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(TEST_BUCKET);
byte[] CONTENT =
RandomStringUtils.randomAscii(OBJ_SIZE).getBytes(Charset.defaultCharset());

testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE);
testFile = File.createTempFile("SplittingPublisherTest", UUID.randomUUID().toString());
Files.write(testFile.toPath(), CONTENT);
mpuS3Client = new MultipartS3AsyncClient(s3Async);
}

Expand All @@ -75,4 +84,19 @@ void putObject_fileRequestBody_objectSentCorrectly() throws Exception {
assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}

@Test
@Timeout(value = 30, unit = SECONDS)
void putObject_byteAsyncRequestBody_objectSentCorrectly() throws Exception {
byte[] bytes = RandomStringUtils.randomAscii(OBJ_SIZE).getBytes(Charset.defaultCharset());
AsyncRequestBody body = AsyncRequestBody.fromBytes(bytes);
mpuS3Client.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();

ResponseInputStream<GetObjectResponse> objContent = S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());

assertThat(objContent.response().contentLength()).isEqualTo(OBJ_SIZE);
byte[] expectedSum = ChecksumUtils.computeCheckSum(new ByteArrayInputStream(bytes));
assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}

}