Skip to content

CRT S3 Client PutObject #2328

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
Mar 18, 2021
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
2 changes: 1 addition & 1 deletion services/s3/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<dependency>
<groupId>software.amazon.awssdk.crt</groupId>
<artifactId>aws-crt</artifactId>
<version>${awscrt.version}</version>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package software.amazon.awssdk.services.s3;

import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import io.reactivex.Flowable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.utils.ChecksumUtils;
import software.amazon.awssdk.testutils.RandomTempFile;

public class CrtClientIntegrationTest extends S3IntegrationTestBase {
private static final String TEST_BUCKET = temporaryBucketName(CrtClientIntegrationTest.class);
private static final String TEST_KEY = "8mib_file.dat";
private static final int OBJ_SIZE = 8 * 1024 * 1024;

private static RandomTempFile testFile;

private S3CrtAsyncClient s3Crt;

@BeforeClass
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(TEST_BUCKET);

testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE);
}

@Before
public void methodSetup() {
s3Crt = S3CrtAsyncClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(DEFAULT_REGION)
.build();
}

@After
public void methodTeardown() {
s3Crt.close();
}

@AfterClass
public static void teardown() throws IOException {
deleteBucketAndAllContents(TEST_BUCKET);
Files.delete(testFile.toPath());
}

@Test
public void putObject_fileRequestBody_objectSentCorrectly() throws IOException, NoSuchAlgorithmException {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();

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

byte[] expectedSum = ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath()));

assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}

@Test
public void putObject_byteBufferBody_objectSentCorrectly() throws IOException, NoSuchAlgorithmException {
byte[] data = new byte[16384];
new Random().nextBytes(data);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);

AsyncRequestBody body = AsyncRequestBody.fromByteBuffer(byteBuffer);

s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();

ResponseBytes<GetObjectResponse> responseBytes = s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toBytes());

byte[] expectedSum = ChecksumUtils.computeCheckSum(byteBuffer);

assertThat(ChecksumUtils.computeCheckSum(responseBytes.asByteBuffer())).isEqualTo(expectedSum);
}

@Test
public void putObject_customRequestBody_objectSentCorrectly() throws IOException, NoSuchAlgorithmException {
Random rng = new Random();
int bufferSize = 16384;
int nBuffers = 15;
List<ByteBuffer> bodyData = Stream.generate(() -> {
byte[] data = new byte[bufferSize];
rng.nextBytes(data);
return ByteBuffer.wrap(data);
}).limit(nBuffers).collect(Collectors.toList());

long contentLength = bufferSize * nBuffers;

byte[] expectedSum = ChecksumUtils.computeCheckSum(bodyData);

Flowable<ByteBuffer> publisher = Flowable.fromIterable(bodyData);

AsyncRequestBody customRequestBody = new AsyncRequestBody() {
@Override
public Optional<Long> contentLength() {
return Optional.of(contentLength);
}

@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
publisher.subscribe(subscriber);
}
};

s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), customRequestBody).join();

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


assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static software.amazon.awssdk.services.s3.internal.S3CrtUtils.createCrtCredentialsProvider;

import com.amazonaws.s3.RequestDataSupplier;
import com.amazonaws.s3.S3NativeClient;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
Expand All @@ -26,6 +27,11 @@
import software.amazon.awssdk.services.s3.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import com.amazonaws.s3.model.PutObjectOutput;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.internal.s3crt.RequestDataSupplierAdapter;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

@SdkInternalApi
public final class DefaultS3CrtAsyncClient implements S3CrtAsyncClient {
Expand Down Expand Up @@ -74,6 +80,20 @@ public <ReturnT> CompletableFuture<ReturnT> getObject(
return future;
}

public CompletableFuture<PutObjectResponse> putObject(PutObjectRequest putObjectRequest, AsyncRequestBody requestBody) {
com.amazonaws.s3.model.PutObjectRequest adaptedRequest = S3CrtUtils.toCrtPutObjectRequest(putObjectRequest);

if (adaptedRequest.contentLength() == null && requestBody.contentLength().isPresent()) {
adaptedRequest = adaptedRequest.toBuilder().contentLength(requestBody.contentLength().get())
.build();
}

CompletableFuture<PutObjectOutput> putObjectOutputCompletableFuture = s3NativeClient.putObject(adaptedRequest,
adaptToDataSupplier(requestBody));

return putObjectOutputCompletableFuture.thenApply(S3CrtUtils::fromCrtPutObjectOutput);
}

@Override
public String serviceName() {
return "s3";
Expand All @@ -84,4 +104,8 @@ public void close() {
s3NativeClient.close();
configuration.close();
}

private static RequestDataSupplier adaptToDataSupplier(AsyncRequestBody requestBody) {
return new RequestDataSupplierAdapter(requestBody);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@

package software.amazon.awssdk.services.s3.internal;

import com.amazonaws.s3.model.ObjectCannedACL;
import com.amazonaws.s3.model.ObjectLockLegalHoldStatus;
import com.amazonaws.s3.model.ObjectLockMode;
import com.amazonaws.s3.model.PutObjectOutput;
import com.amazonaws.s3.model.RequestPayer;
import com.amazonaws.s3.model.ServerSideEncryption;
import com.amazonaws.s3.model.StorageClass;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
Expand All @@ -23,6 +30,8 @@
import software.amazon.awssdk.crt.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

@SdkInternalApi
public final class S3CrtUtils {
Expand Down Expand Up @@ -64,21 +73,82 @@ public static com.amazonaws.s3.model.GetObjectRequest adaptGetObjectRequest(GetO
// TODO: codegen
public static GetObjectResponse adaptGetObjectOutput(com.amazonaws.s3.model.GetObjectOutput response) {
return GetObjectResponse.builder()
.bucketKeyEnabled(response.bucketKeyEnabled())
.acceptRanges(response.acceptRanges())
.contentDisposition(response.contentDisposition())
.cacheControl(response.cacheControl())
.contentEncoding(response.contentEncoding())
.contentLanguage(response.contentLanguage())
.contentRange(response.contentRange())
.contentLength(response.contentLength())
.contentType(response.contentType())
.deleteMarker(response.deleteMarker())
.eTag(response.eTag())
.expiration(response.expiration())
.expires(response.expires())
.lastModified(response.lastModified())
.metadata(response.metadata())
.build();
.bucketKeyEnabled(response.bucketKeyEnabled())
.acceptRanges(response.acceptRanges())
.contentDisposition(response.contentDisposition())
.cacheControl(response.cacheControl())
.contentEncoding(response.contentEncoding())
.contentLanguage(response.contentLanguage())
.contentRange(response.contentRange())
.contentLength(response.contentLength())
.contentType(response.contentType())
.deleteMarker(response.deleteMarker())
.eTag(response.eTag())
.expiration(response.expiration())
.expires(response.expires())
.lastModified(response.lastModified())
.metadata(response.metadata())
.build();
}

//TODO: codegen
public static com.amazonaws.s3.model.PutObjectRequest toCrtPutObjectRequest(PutObjectRequest sdkPutObject) {
return com.amazonaws.s3.model.PutObjectRequest.builder()
.contentLength(sdkPutObject.contentLength())
.aCL(ObjectCannedACL.fromValue(sdkPutObject.aclAsString()))
.bucket(sdkPutObject.bucket())
.key(sdkPutObject.key())
.bucketKeyEnabled(sdkPutObject.bucketKeyEnabled())
.cacheControl(sdkPutObject.cacheControl())
.contentDisposition(sdkPutObject.contentDisposition())
.contentEncoding(sdkPutObject.contentEncoding())
.contentLanguage(sdkPutObject.contentLanguage())
.contentMD5(sdkPutObject.contentMD5())
.contentType(sdkPutObject.contentType())
.expectedBucketOwner(sdkPutObject.expectedBucketOwner())
.expires(sdkPutObject.expires())
.grantFullControl(sdkPutObject.grantFullControl())
.grantRead(sdkPutObject.grantRead())
.grantReadACP(sdkPutObject.grantReadACP())
.grantWriteACP(sdkPutObject.grantWriteACP())
.metadata(sdkPutObject.metadata())
.objectLockLegalHoldStatus(ObjectLockLegalHoldStatus.fromValue(sdkPutObject.objectLockLegalHoldStatusAsString()))
.objectLockMode(ObjectLockMode.fromValue(sdkPutObject.objectLockModeAsString()))
.objectLockRetainUntilDate(sdkPutObject.objectLockRetainUntilDate())
.requestPayer(RequestPayer.fromValue(sdkPutObject.requestPayerAsString()))
.serverSideEncryption(ServerSideEncryption.fromValue(sdkPutObject.requestPayerAsString()))
.sSECustomerAlgorithm(sdkPutObject.sseCustomerAlgorithm())
.sSECustomerKey(sdkPutObject.sseCustomerKey())
.sSECustomerKeyMD5(sdkPutObject.sseCustomerKeyMD5())
.sSEKMSEncryptionContext(sdkPutObject.ssekmsEncryptionContext())
.sSEKMSKeyId(sdkPutObject.ssekmsKeyId())
.storageClass(StorageClass.fromValue(sdkPutObject.storageClassAsString()))
.tagging(sdkPutObject.tagging())
.websiteRedirectLocation(sdkPutObject.websiteRedirectLocation())
.build();
}

//TODO: codegen
public static PutObjectResponse fromCrtPutObjectOutput(PutObjectOutput crtPutObjectOutput) {
// TODO: Provide the HTTP request-level data (e.g. response metadata, HTTP response)
PutObjectResponse.Builder builder = PutObjectResponse.builder()
.bucketKeyEnabled(crtPutObjectOutput.bucketKeyEnabled())
.eTag(crtPutObjectOutput.eTag())
.expiration(crtPutObjectOutput.expiration())
.sseCustomerAlgorithm(crtPutObjectOutput.sSECustomerAlgorithm())
.sseCustomerKeyMD5(crtPutObjectOutput.sSECustomerKeyMD5())
.ssekmsEncryptionContext(crtPutObjectOutput.sSEKMSEncryptionContext())
.ssekmsKeyId(crtPutObjectOutput.sSEKMSKeyId())
.versionId(crtPutObjectOutput.versionId());

if (crtPutObjectOutput.requestCharged() != null) {
builder.requestCharged(crtPutObjectOutput.requestCharged().value());
}

if (crtPutObjectOutput.serverSideEncryption() != null) {
builder.serverSideEncryption(crtPutObjectOutput.serverSideEncryption().value());
}

return builder.build();
}
}
Loading