You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by da...@apache.org on 2022/11/04 22:05:33 UTC
[flink-connector-aws] branch main updated: [FLINK-24229][Connectors][DynamoDB] - Add AWS DynamoDB connector
This is an automated email from the ASF dual-hosted git repository.
dannycranmer pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/flink-connector-aws.git
The following commit(s) were added to refs/heads/main by this push:
new 11bcbf9 [FLINK-24229][Connectors][DynamoDB] - Add AWS DynamoDB connector
11bcbf9 is described below
commit 11bcbf9536b6057e314bccb448d2ec379ebd6df6
Author: nir.tsruya <ni...@klarna.com>
AuthorDate: Thu Aug 11 14:09:24 2022 +0200
[FLINK-24229][Connectors][DynamoDB] - Add AWS DynamoDB connector
Co-authored-by: Yuri Gusev <yu...@gmail.com>
---
.../23e251e7-3783-4611-867f-207bf0d3bf73 | 0
.../87c5201e-65c7-4595-944e-ac151c93834d | 0
.../archunit-violations/stored.rules | 4 +
flink-connector-dynamodb/pom.xml | 71 ++-
.../dynamodb/sink/DynamoDbConfigConstants.java | 32 ++
.../connectors/dynamodb/sink/DynamoDbSink.java | 164 +++++++
.../dynamodb/sink/DynamoDbSinkBuilder.java | 161 +++++++
.../dynamodb/sink/DynamoDbSinkException.java | 52 ++
.../dynamodb/sink/DynamoDbSinkWriter.java | 319 +++++++++++++
.../dynamodb/sink/DynamoDbWriteRequest.java | 99 ++++
.../dynamodb/sink/DynamoDbWriteRequestType.java | 74 +++
.../sink/DynamoDbWriterStateSerializer.java | 54 +++
.../sink/InvalidConfigurationException.java | 29 ++
.../dynamodb/sink/InvalidRequestException.java | 29 ++
.../dynamodb/util/DynamoDbSerializationUtil.java | 197 ++++++++
.../connectors/dynamodb/util/DynamoDbType.java | 115 +++++
.../dynamodb/util/PrimaryKeyBuilder.java | 127 +++++
.../src/main/resources/META-INF/licenses/.gitkeep | 0
.../src/main/resources/META-INF/services/.gitkeep | 0
.../src/main/resources/log4j2.properties | 25 +
.../architecture/TestCodeArchitectureTest.java | 40 ++
.../dynamodb/sink/DynamoDbSinkBuilderTest.java | 124 +++++
.../dynamodb/sink/DynamoDbSinkITCase.java | 528 +++++++++++++++++++++
.../sink/DynamoDbWriterStateSerializerTest.java | 65 +++
.../sink/TestDynamoDbElementConverter.java | 40 ++
.../dynamodb/sink/TestRequestMapper.java | 49 ++
.../dynamodb/sink/examples/SinkIntoDynamoDb.java | 96 ++++
.../dynamodb/testutils/DynamoDBHelpers.java | 100 ++++
.../dynamodb/testutils/DynamoDbContainer.java | 164 +++++++
.../connectors/dynamodb/testutils/Item.java | 46 ++
.../connectors/dynamodb/testutils/Items.java | 47 ++
.../dynamodb/util/DockerImageVersions.java | 32 ++
.../util/DynamoDbSerializationUtilTest.java | 125 +++++
.../dynamodb/util/PrimaryKeyBuilderTest.java | 159 +++++++
.../src/test/resources/archunit.properties | 31 ++
.../src/test/resources/log4j2-test.properties | 29 ++
pom.xml | 1 +
37 files changed, 3227 insertions(+), 1 deletion(-)
diff --git a/flink-connector-dynamodb/archunit-violations/23e251e7-3783-4611-867f-207bf0d3bf73 b/flink-connector-dynamodb/archunit-violations/23e251e7-3783-4611-867f-207bf0d3bf73
new file mode 100644
index 0000000..e69de29
diff --git a/flink-connector-dynamodb/archunit-violations/87c5201e-65c7-4595-944e-ac151c93834d b/flink-connector-dynamodb/archunit-violations/87c5201e-65c7-4595-944e-ac151c93834d
new file mode 100644
index 0000000..e69de29
diff --git a/flink-connector-dynamodb/archunit-violations/stored.rules b/flink-connector-dynamodb/archunit-violations/stored.rules
new file mode 100644
index 0000000..97fcafc
--- /dev/null
+++ b/flink-connector-dynamodb/archunit-violations/stored.rules
@@ -0,0 +1,4 @@
+#
+#Thu Aug 11 14:04:41 CEST 2022
+ITCASE\ tests\ should\ use\ a\ MiniCluster\ resource\ or\ extension=23e251e7-3783-4611-867f-207bf0d3bf73
+Tests\ inheriting\ from\ AbstractTestBase\ should\ have\ name\ ending\ with\ ITCase=87c5201e-65c7-4595-944e-ac151c93834d
diff --git a/flink-connector-dynamodb/pom.xml b/flink-connector-dynamodb/pom.xml
index 41ed228..09fef61 100644
--- a/flink-connector-dynamodb/pom.xml
+++ b/flink-connector-dynamodb/pom.xml
@@ -26,13 +26,15 @@ under the License.
<parent>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-dynamodb-parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
+ <version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>flink-connector-dynamodb</artifactId>
<name>Flink : Connectors : Amazon DynamoDB</name>
+ <packaging>jar</packaging>
+
<dependencyManagement>
<dependencies>
<dependency>
@@ -44,4 +46,71 @@ under the License.
</dependencies>
</dependencyManagement>
+ <dependencies>
+ <!-- Core -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-streaming-java</artifactId>
+ <version>${flink.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-aws-base</artifactId>
+ <version>${flink.version}</version>
+ </dependency>
+
+ <!-- Flink Connector DynamoDB Dependencies -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>dynamodb</artifactId>
+ </dependency>
+
+ <!-- Test dependencies -->
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-test-utils</artifactId>
+ <version>${flink.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-base</artifactId>
+ <version>${flink.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-connector-aws-base</artifactId>
+ <version>${flink.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-architecture-tests-base</artifactId>
+ <version>${flink.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.flink</groupId>
+ <artifactId>flink-architecture-tests-test</artifactId>
+ <version>${flink.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
</project>
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbConfigConstants.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbConfigConstants.java
new file mode 100644
index 0000000..03be741
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbConfigConstants.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Defaults for {@link DynamoDbSinkWriter}. */
+@PublicEvolving
+public class DynamoDbConfigConstants {
+
+ public static final String BASE_DYNAMODB_USER_AGENT_PREFIX_FORMAT =
+ "Apache Flink %s (%s) DynamoDb Connector";
+
+ /** DynamoDb identifier for user agent prefix. */
+ public static final String DYNAMODB_CLIENT_USER_AGENT_PREFIX =
+ "aws.dynamodb.client.user-agent-prefix";
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSink.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSink.java
new file mode 100644
index 0000000..c6b208b
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSink.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBase;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.core.io.SimpleVersionedSerializer;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.flink.util.Preconditions.checkArgument;
+import static org.apache.flink.util.Preconditions.checkNotNull;
+
+/**
+ * A DynamoDB Sink that performs async requests against a destination table using the buffering
+ * protocol specified in {@link AsyncSinkBase}.
+ *
+ * <p>The sink internally uses a {@link
+ * software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient} to communicate with the AWS
+ * endpoint.
+ *
+ * <p>The behaviour of the buffering may be specified by providing configuration during the sink
+ * build time.
+ *
+ * <ul>
+ * <li>{@code maxBatchSize}: the maximum size of a batch of entries that may be written to
+ * DynamoDb. DynamoDB client supports only up to 25 elements in the batch.
+ * <li>{@code maxInFlightRequests}: the maximum number of in flight requests that may exist, if
+ * any more in flight requests need to be initiated once the maximum has been reached, then it
+ * will be blocked until some have completed
+ * <li>{@code maxBufferedRequests}: the maximum number of elements held in the buffer, requests to
+ * sink will backpressure while the number of elements in the buffer is at the maximum
+ * <li>{@code maxBatchSizeInBytes}: this setting will not have any effect on DynamoDBSink batch
+ * implementation
+ * <li>{@code maxTimeInBufferMS}: the maximum amount of time an entry is allowed to live in the
+ * buffer, if any element reaches this age, the entire buffer will be flushed immediately
+ * <li>{@code maxRecordSizeInBytes}: this setting will not have any effect on DynamoDBSink batch
+ * implementation
+ * <li>{@code failOnError}: when an exception is encountered while persisting to DynamoDb, the job
+ * will fail immediately if failOnError is set
+ * <li>{@code overwriteByPartitionKeys}: list of attribute key names for the sink to deduplicate
+ * on if you want to bypass the no duplication limitation of a single batch write request.
+ * Batching DynamoDB sink will drop request items in the buffer if their primary
+ * keys(composite) values are the same as the newly added ones. The newer request item in a
+ * single batch takes precedence.
+ * </ul>
+ *
+ * <p>Please see the writer implementation in {@link DynamoDbSinkWriter}
+ *
+ * @param <InputT> Type of the elements handled by this sink
+ */
+@PublicEvolving
+public class DynamoDbSink<InputT> extends AsyncSinkBase<InputT, DynamoDbWriteRequest> {
+
+ private final Properties dynamoDbClientProperties;
+ private final boolean failOnError;
+ private final String tableName;
+ private final List<String> overwriteByPartitionKeys;
+
+ protected DynamoDbSink(
+ ElementConverter<InputT, DynamoDbWriteRequest> elementConverter,
+ int maxBatchSize,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ long maxBatchSizeInBytes,
+ long maxTimeInBufferMS,
+ long maxRecordSizeInBytes,
+ boolean failOnError,
+ String tableName,
+ List<String> overwriteByPartitionKeys,
+ Properties dynamoDbClientProperties) {
+ super(
+ elementConverter,
+ maxBatchSize,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInBytes,
+ maxTimeInBufferMS,
+ maxRecordSizeInBytes);
+ checkNotNull(
+ tableName,
+ "Destination table name must be set when initializing the DynamoDB Sink.");
+ checkArgument(
+ !tableName.isEmpty(),
+ "Destination table name must be set when initializing the DynamoDB Sink.");
+ checkArgument(
+ maxBatchSize <= 25,
+ "DynamoDB client supports only up to 25 elements in the batch.");
+ checkNotNull(dynamoDbClientProperties, "DynamoDB client properties must be set.");
+ this.failOnError = failOnError;
+ this.tableName = tableName;
+ this.overwriteByPartitionKeys = overwriteByPartitionKeys;
+ this.dynamoDbClientProperties = dynamoDbClientProperties;
+ }
+
+ /**
+ * Create a {@link DynamoDbSinkBuilder} to construct a new {@link DynamoDbSink}.
+ *
+ * @param <InputT> type of incoming records
+ * @return {@link DynamoDbSinkBuilder}
+ */
+ public static <InputT> DynamoDbSinkBuilder<InputT> builder() {
+ return new DynamoDbSinkBuilder<>();
+ }
+
+ @Internal
+ @Override
+ public StatefulSinkWriter<InputT, BufferedRequestState<DynamoDbWriteRequest>> createWriter(
+ InitContext context) throws IOException {
+ return restoreWriter(context, Collections.emptyList());
+ }
+
+ @Internal
+ @Override
+ public StatefulSinkWriter<InputT, BufferedRequestState<DynamoDbWriteRequest>> restoreWriter(
+ InitContext context,
+ Collection<BufferedRequestState<DynamoDbWriteRequest>> recoveredState)
+ throws IOException {
+ return new DynamoDbSinkWriter<>(
+ getElementConverter(),
+ context,
+ getMaxBatchSize(),
+ getMaxInFlightRequests(),
+ getMaxBufferedRequests(),
+ getMaxBatchSizeInBytes(),
+ getMaxTimeInBufferMS(),
+ getMaxRecordSizeInBytes(),
+ failOnError,
+ tableName,
+ overwriteByPartitionKeys,
+ dynamoDbClientProperties,
+ recoveredState);
+ }
+
+ @Internal
+ @Override
+ public SimpleVersionedSerializer<BufferedRequestState<DynamoDbWriteRequest>>
+ getWriterStateSerializer() {
+ return new DynamoDbWriterStateSerializer();
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilder.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilder.java
new file mode 100644
index 0000000..6c955f0
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilder.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.connector.base.sink.AsyncSinkBaseBuilder;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Properties;
+
+/**
+ * Builder to construct {@link DynamoDbSink}.
+ *
+ * <p>The following example shows the minimum setup to create a {@link DynamoDbSink} that writes
+ * records into DynamoDb
+ *
+ * <pre>{@code
+ * private static class DummyDynamoDbElementConverter
+ * implements ElementConverter<String, DynamoDbWriteRequest> {
+ *
+ * @Override
+ * public DynamoDbWriteRequest apply(String s, SinkWriter.Context context) {
+ * final Map<String, AttributeValue> item = new HashMap<>();
+ * item.put("your-key", AttributeValue.builder().s(s).build());
+ * return DynamoDbWriteRequest.builder()
+ * .setItem(item)
+ * .setType(DynamoDbWriteRequestType.PUT)
+ * .build();
+ * }
+ * }
+ *
+ * DynamoDbSink<String> dynamoDbSink =
+ * DynamoDbSink.<String>builder()
+ * .setElementConverter(new DummyDynamoDbElementConverter())
+ * .setDestinationTableName("your-table-name")
+ * .build();
+ * }</pre>
+ *
+ * <p>If the following parameters are not set in this builder, the following defaults will be used:
+ *
+ * <ul>
+ * <li>{@code maxBatchSize} will be 25
+ * <li>{@code maxInFlightRequests} will be 50
+ * <li>{@code maxBufferedRequests} will be 10000
+ * <li>{@code maxBatchSizeInBytes} setting is not supported by this implementation
+ * <li>{@code maxTimeInBufferMS} will be 5000ms
+ * <li>{@code maxRecordSizeInBytes} setting is not supported by this implementation
+ * <li>{@code failOnError} will be false
+ * <li>{@code destinationTableName} destination table for the sink
+ * <li>{@code overwriteByPartitionKeys} will be empty meaning no records deduplication will be
+ * performed by the batch sink
+ * </ul>
+ *
+ * @param <InputT> type of elements that should be persisted in the destination
+ */
+@PublicEvolving
+public class DynamoDbSinkBuilder<InputT>
+ extends AsyncSinkBaseBuilder<InputT, DynamoDbWriteRequest, DynamoDbSinkBuilder<InputT>> {
+
+ private static final int DEFAULT_MAX_BATCH_SIZE = 25;
+ private static final int DEFAULT_MAX_IN_FLIGHT_REQUESTS = 50;
+ private static final int DEFAULT_MAX_BUFFERED_REQUESTS = 10000;
+
+ // Max record size in bytes and max batch size in bytes are not supported by this implementation
+ private static final long DEFAULT_MAX_RECORD_SIZE_IN_B = 400 * 1000;
+ private static final long DEFAULT_MAX_BATCH_SIZE_IN_B = 16 * 1000 * 1000;
+
+ private static final long DEFAULT_MAX_TIME_IN_BUFFER_MS = 5000;
+ private static final boolean DEFAULT_FAIL_ON_ERROR = false;
+
+ private boolean failOnError;
+ private Properties dynamodbClientProperties;
+
+ private ElementConverter<InputT, DynamoDbWriteRequest> elementConverter;
+ private String tableName;
+
+ private List<String> overwriteByPartitionKeys;
+
+ public DynamoDbSinkBuilder<InputT> setDynamoDbProperties(Properties properties) {
+ this.dynamodbClientProperties = properties;
+ return this;
+ }
+
+ public DynamoDbSinkBuilder<InputT> setElementConverter(
+ ElementConverter<InputT, DynamoDbWriteRequest> elementConverter) {
+ this.elementConverter = elementConverter;
+ return this;
+ }
+
+ /** Destination table name for the DynamoDB sink. */
+ public DynamoDbSinkBuilder<InputT> setDestinationTableName(String tableName) {
+ this.tableName = tableName;
+ return this;
+ }
+
+ /**
+ * @param overwriteByPartitionKeys list of attribute key names for the sink to deduplicate on if
+ * you want to bypass the no duplication limitation of a single batch write request.
+ * Batching DynamoDB sink will drop request items in the buffer if their primary
+ * keys(composite) values are the same as the newly added ones. The newer request item in a
+ * single batch takes precedence.
+ */
+ public DynamoDbSinkBuilder<InputT> setOverwriteByPartitionKeys(
+ List<String> overwriteByPartitionKeys) {
+ this.overwriteByPartitionKeys = overwriteByPartitionKeys;
+ return this;
+ }
+
+ public DynamoDbSinkBuilder<InputT> setFailOnError(boolean failOnError) {
+ this.failOnError = failOnError;
+ return this;
+ }
+
+ @Override
+ public DynamoDbSinkBuilder<InputT> setMaxBatchSizeInBytes(long maxBatchSizeInBytes) {
+ throw new InvalidConfigurationException(
+ "Max batch size in bytes is not supported by the DynamoDB sink implementation.");
+ }
+
+ @Override
+ public DynamoDbSinkBuilder<InputT> setMaxRecordSizeInBytes(long maxRecordSizeInBytes) {
+ throw new InvalidConfigurationException(
+ "Max record size in bytes is not supported by the DynamoDB sink implementation.");
+ }
+
+ @Override
+ public DynamoDbSink<InputT> build() {
+ return new DynamoDbSink<>(
+ elementConverter,
+ Optional.ofNullable(getMaxBatchSize()).orElse(DEFAULT_MAX_BATCH_SIZE),
+ Optional.ofNullable(getMaxInFlightRequests())
+ .orElse(DEFAULT_MAX_IN_FLIGHT_REQUESTS),
+ Optional.ofNullable(getMaxBufferedRequests()).orElse(DEFAULT_MAX_BUFFERED_REQUESTS),
+ Optional.ofNullable(getMaxBatchSizeInBytes()).orElse(DEFAULT_MAX_BATCH_SIZE_IN_B),
+ Optional.ofNullable(getMaxTimeInBufferMS()).orElse(DEFAULT_MAX_TIME_IN_BUFFER_MS),
+ Optional.ofNullable(getMaxRecordSizeInBytes()).orElse(DEFAULT_MAX_RECORD_SIZE_IN_B),
+ Optional.of(failOnError).orElse(DEFAULT_FAIL_ON_ERROR),
+ tableName,
+ Optional.ofNullable(overwriteByPartitionKeys).orElse(new ArrayList<>()),
+ Optional.ofNullable(dynamodbClientProperties).orElse(new Properties()));
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkException.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkException.java
new file mode 100644
index 0000000..10a48af
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkException.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Exception is thrown when DynamoDb sink failed to write data. */
+@PublicEvolving
+public class DynamoDbSinkException extends RuntimeException {
+ public DynamoDbSinkException(String message) {
+ super(message);
+ }
+
+ public DynamoDbSinkException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * When the flag {@code failOnError} is set in {@link DynamoDbSinkWriter}, this exception is
+ * raised as soon as any non-recoverable exception occurs.
+ */
+ @PublicEvolving
+ static class DynamoDbSinkFailFastException extends DynamoDbSinkException {
+
+ public DynamoDbSinkFailFastException() {
+ super(
+ "Encountered an exception while persisting records, not retrying due to {failOnError} being set.");
+ }
+
+ public DynamoDbSinkFailFastException(final Throwable cause) {
+ super(
+ "Encountered an exception while persisting records, not retrying due to {failOnError} being set.",
+ cause);
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkWriter.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkWriter.java
new file mode 100644
index 0000000..bbbc201
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkWriter.java
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.connector.sink2.Sink.InitContext;
+import org.apache.flink.connector.aws.config.AWSConfigConstants;
+import org.apache.flink.connector.aws.util.AWSAsyncSinkUtil;
+import org.apache.flink.connector.aws.util.AWSGeneralUtil;
+import org.apache.flink.connector.base.sink.throwable.FatalExceptionClassifier;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriter;
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.metrics.groups.SinkWriterMetricGroup;
+import org.apache.flink.streaming.connectors.dynamodb.util.PrimaryKeyBuilder;
+import org.apache.flink.util.CollectionUtil;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableMap;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;
+import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
+import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
+import software.amazon.awssdk.services.dynamodb.model.PutRequest;
+import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Consumer;
+
+import static org.apache.flink.connector.aws.util.AWSCredentialFatalExceptionClassifiers.getInvalidCredentialsExceptionClassifier;
+import static org.apache.flink.connector.aws.util.AWSCredentialFatalExceptionClassifiers.getSdkClientMisconfiguredExceptionClassifier;
+import static org.apache.flink.connector.base.sink.writer.AsyncSinkFatalExceptionClassifiers.getInterruptedExceptionClassifier;
+
+/**
+ * Sink writer created by {@link DynamoDbSink} to write to DynamoDB. More details on the operation
+ * of this sink writer may be found in the doc for {@link DynamoDbSink}. More details on the
+ * internals of this sink writer may be found in {@link AsyncSinkWriter}.
+ *
+ * <p>The {@link DynamoDbAsyncClient} used here may be configured in the standard way for the AWS
+ * SDK 2.x. e.g. the provision of {@code AWS_REGION}, {@code AWS_ACCESS_KEY_ID} and {@code
+ * AWS_SECRET_ACCESS_KEY} through environment variables etc.
+ */
+@Internal
+class DynamoDbSinkWriter<InputT> extends AsyncSinkWriter<InputT, DynamoDbWriteRequest> {
+ private static final Logger LOG = LoggerFactory.getLogger(DynamoDbSinkWriter.class);
+
+ private static final FatalExceptionClassifier RESOURCE_NOT_FOUND_EXCEPTION_CLASSIFIER =
+ FatalExceptionClassifier.withRootCauseOfType(
+ ResourceNotFoundException.class,
+ err ->
+ new DynamoDbSinkException(
+ "Encountered non-recoverable exception relating to not being able to find the specified resources",
+ err));
+
+ private static final FatalExceptionClassifier CONDITIONAL_CHECK_FAILED_EXCEPTION_CLASSIFIER =
+ FatalExceptionClassifier.withRootCauseOfType(
+ ConditionalCheckFailedException.class,
+ err ->
+ new DynamoDbSinkException(
+ "Encountered non-recoverable exception relating to failed conditional check",
+ err));
+
+ /* Validation exceptions are not retryable. See https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html. */
+ private static final FatalExceptionClassifier VALIDATION_EXCEPTION_CLASSIFIER =
+ new FatalExceptionClassifier(
+ (err) ->
+ err instanceof DynamoDbException
+ && ((DynamoDbException) err)
+ .toBuilder()
+ .awsErrorDetails()
+ .errorCode()
+ .equalsIgnoreCase("ValidationException"),
+ err ->
+ new DynamoDbSinkException(
+ "Encountered non-recoverable exception because of DynamoDB request validation",
+ err));
+
+ private static final FatalExceptionClassifier DYNAMODB_FATAL_EXCEPTION_CLASSIFIER =
+ FatalExceptionClassifier.createChain(
+ getInterruptedExceptionClassifier(),
+ getInvalidCredentialsExceptionClassifier(),
+ RESOURCE_NOT_FOUND_EXCEPTION_CLASSIFIER,
+ CONDITIONAL_CHECK_FAILED_EXCEPTION_CLASSIFIER,
+ VALIDATION_EXCEPTION_CLASSIFIER,
+ getSdkClientMisconfiguredExceptionClassifier());
+
+ /* A counter for the total number of records that have encountered an error during put */
+ private final Counter numRecordsSendErrorsCounter;
+
+ /* A counter for the total number of records that were returned by DynamoDB as unprocessed and were retried */
+ private final Counter numRecordsSendPartialFailure;
+
+ /* The sink writer metric group */
+ private final SinkWriterMetricGroup metrics;
+
+ /* The asynchronous http client for the asynchronous DynamoDb client */
+ private final SdkAsyncHttpClient httpClient;
+ private final DynamoDbAsyncClient client;
+ private final boolean failOnError;
+ private final String tableName;
+
+ private final List<String> overwriteByPartitionKeys;
+
+ public DynamoDbSinkWriter(
+ ElementConverter<InputT, DynamoDbWriteRequest> elementConverter,
+ InitContext context,
+ int maxBatchSize,
+ int maxInFlightRequests,
+ int maxBufferedRequests,
+ long maxBatchSizeInBytes,
+ long maxTimeInBufferMS,
+ long maxRecordSizeInBytes,
+ boolean failOnError,
+ String tableName,
+ List<String> overwriteByPartitionKeys,
+ Properties dynamoDbClientProperties,
+ Collection<BufferedRequestState<DynamoDbWriteRequest>> states) {
+ super(
+ elementConverter,
+ context,
+ maxBatchSize,
+ maxInFlightRequests,
+ maxBufferedRequests,
+ maxBatchSizeInBytes,
+ maxTimeInBufferMS,
+ maxRecordSizeInBytes,
+ states);
+ this.failOnError = failOnError;
+ this.tableName = tableName;
+ this.overwriteByPartitionKeys = overwriteByPartitionKeys;
+ this.metrics = context.metricGroup();
+ this.numRecordsSendErrorsCounter = metrics.getNumRecordsSendErrorsCounter();
+ this.numRecordsSendPartialFailure = metrics.counter("numRecordsSendPartialFailure");
+ this.httpClient =
+ AWSGeneralUtil.createAsyncHttpClient(
+ overrideClientProperties(dynamoDbClientProperties));
+ this.client = buildClient(dynamoDbClientProperties, httpClient);
+ }
+
+ private Properties overrideClientProperties(Properties dynamoDbClientProperties) {
+ Properties overridenProperties = new Properties();
+ overridenProperties.putAll(dynamoDbClientProperties);
+
+ // Specify HTTP1_1 protocol since DynamoDB endpoint doesn't support HTTP2
+ overridenProperties.put(AWSConfigConstants.HTTP_PROTOCOL_VERSION, "HTTP1_1");
+ return overridenProperties;
+ }
+
+ private DynamoDbAsyncClient buildClient(
+ Properties dynamoDbClientProperties, SdkAsyncHttpClient httpClient) {
+ AWSGeneralUtil.validateAwsCredentials(dynamoDbClientProperties);
+
+ return AWSAsyncSinkUtil.createAwsAsyncClient(
+ dynamoDbClientProperties,
+ httpClient,
+ DynamoDbAsyncClient.builder(),
+ DynamoDbConfigConstants.BASE_DYNAMODB_USER_AGENT_PREFIX_FORMAT,
+ DynamoDbConfigConstants.DYNAMODB_CLIENT_USER_AGENT_PREFIX);
+ }
+
+ @Override
+ protected void submitRequestEntries(
+ List<DynamoDbWriteRequest> requestEntries,
+ Consumer<List<DynamoDbWriteRequest>> requestResultConsumer) {
+
+ List<WriteRequest> items = new ArrayList<>();
+
+ if (CollectionUtil.isNullOrEmpty(overwriteByPartitionKeys)) {
+ for (DynamoDbWriteRequest request : requestEntries) {
+ items.add(convertToWriteRequest(request));
+ }
+ } else {
+ // deduplication needed
+ Map<String, WriteRequest> container = new HashMap<>();
+ PrimaryKeyBuilder keyBuilder = new PrimaryKeyBuilder(overwriteByPartitionKeys);
+ for (DynamoDbWriteRequest request : requestEntries) {
+ WriteRequest req = convertToWriteRequest(request);
+ container.put(keyBuilder.build(req), req);
+ }
+ items.addAll(container.values());
+ }
+
+ CompletableFuture<BatchWriteItemResponse> future =
+ client.batchWriteItem(
+ BatchWriteItemRequest.builder()
+ .requestItems(ImmutableMap.of(tableName, items))
+ .build());
+
+ future.whenComplete(
+ (response, err) -> {
+ if (err != null) {
+ handleFullyFailedRequest(err, requestEntries, requestResultConsumer);
+ } else if (!CollectionUtil.isNullOrEmpty(response.unprocessedItems())) {
+ handlePartiallyUnprocessedRequest(response, requestResultConsumer);
+ } else {
+ requestResultConsumer.accept(Collections.emptyList());
+ }
+ });
+ }
+
+ private void handlePartiallyUnprocessedRequest(
+ BatchWriteItemResponse response, Consumer<List<DynamoDbWriteRequest>> requestResult) {
+ List<DynamoDbWriteRequest> unprocessed = new ArrayList<>();
+
+ for (WriteRequest writeRequest : response.unprocessedItems().get(tableName)) {
+ unprocessed.add(convertToDynamoDbWriteRequest(writeRequest));
+ }
+
+ LOG.warn("DynamoDB Sink failed to persist and will retry {} entries.", unprocessed.size());
+ numRecordsSendErrorsCounter.inc(unprocessed.size());
+ numRecordsSendPartialFailure.inc(unprocessed.size());
+
+ requestResult.accept(unprocessed);
+ }
+
+ private void handleFullyFailedRequest(
+ Throwable err,
+ List<DynamoDbWriteRequest> requestEntries,
+ Consumer<List<DynamoDbWriteRequest>> requestResult) {
+ LOG.warn(
+ "DynamoDB Sink failed to persist and will retry {} entries.",
+ requestEntries.size(),
+ err);
+ numRecordsSendErrorsCounter.inc(requestEntries.size());
+
+ if (isRetryable(err.getCause())) {
+ requestResult.accept(requestEntries);
+ }
+ }
+
+ private boolean isRetryable(Throwable err) {
+ if (!DYNAMODB_FATAL_EXCEPTION_CLASSIFIER.isFatal(err, getFatalExceptionCons())) {
+ return false;
+ }
+ if (failOnError) {
+ getFatalExceptionCons()
+ .accept(new DynamoDbSinkException.DynamoDbSinkFailFastException(err));
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ protected long getSizeInBytes(DynamoDbWriteRequest requestEntry) {
+ // dynamodb calculates item size as a sum of all attributes and all values, to calculate it
+ // correctly would be an expensive operation and we would potentially be serializing each
+ // record twice this can be removed after FLINK-29854 is implemented
+ return 0;
+ }
+
+ @Override
+ public void close() {
+ AWSGeneralUtil.closeResources(httpClient, client);
+ }
+
+ private WriteRequest convertToWriteRequest(DynamoDbWriteRequest dynamoDbWriteRequest) {
+ if (dynamoDbWriteRequest.getType() == DynamoDbWriteRequestType.PUT) {
+ return WriteRequest.builder()
+ .putRequest(PutRequest.builder().item(dynamoDbWriteRequest.getItem()).build())
+ .build();
+ } else if (dynamoDbWriteRequest.getType() == DynamoDbWriteRequestType.DELETE) {
+ return WriteRequest.builder()
+ .deleteRequest(
+ DeleteRequest.builder().key(dynamoDbWriteRequest.getItem()).build())
+ .build();
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported DynamoDb Write Request Type. consider updating the convertToWriteRequest method");
+ }
+ }
+
+ private DynamoDbWriteRequest convertToDynamoDbWriteRequest(WriteRequest writeRequest) {
+ if (writeRequest.putRequest() != null) {
+ return DynamoDbWriteRequest.builder()
+ .setItem(writeRequest.putRequest().item())
+ .setType(DynamoDbWriteRequestType.PUT)
+ .build();
+ } else if (writeRequest.deleteRequest() != null) {
+ return DynamoDbWriteRequest.builder()
+ .setItem(writeRequest.deleteRequest().key())
+ .setType(DynamoDbWriteRequestType.DELETE)
+ .build();
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported Write Request, consider updating the convertToDynamoDbWriteRequest method");
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequest.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequest.java
new file mode 100644
index 0000000..4d60052
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequest.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.util.Preconditions;
+
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.io.Serializable;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Represents a single Write Request to DynamoDb. Contains the item to be written as well as the
+ * type of the Write Request (PUT/DELETE)
+ */
+@PublicEvolving
+public class DynamoDbWriteRequest implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final Map<String, AttributeValue> item;
+ private final DynamoDbWriteRequestType type;
+
+ private DynamoDbWriteRequest(Map<String, AttributeValue> item, DynamoDbWriteRequestType type) {
+ this.item = item;
+ this.type = type;
+ }
+
+ public Map<String, AttributeValue> getItem() {
+ return item;
+ }
+
+ public DynamoDbWriteRequestType getType() {
+ return type;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ DynamoDbWriteRequest that = (DynamoDbWriteRequest) o;
+ return item.equals(that.item) && type == that.type;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(item, type);
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for DynamoDbWriteRequest. */
+ public static class Builder {
+ private Map<String, AttributeValue> item;
+ private DynamoDbWriteRequestType type;
+
+ public Builder setItem(Map<String, AttributeValue> item) {
+ this.item = item;
+ return this;
+ }
+
+ public Builder setType(DynamoDbWriteRequestType type) {
+ this.type = type;
+ return this;
+ }
+
+ public DynamoDbWriteRequest build() {
+ Preconditions.checkNotNull(
+ item, "No Item was supplied to the " + "DynamoDbWriteRequest builder.");
+ Preconditions.checkNotNull(
+ type, "No type was supplied to the " + "DynamoDbWriteRequest builder.");
+ return new DynamoDbWriteRequest(item, type);
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequestType.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequestType.java
new file mode 100644
index 0000000..0aea402
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriteRequestType.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/**
+ * Represents a DynamoDb Write Request type. The following types are currently supported
+ *
+ * <ul>
+ * <li>PUT - Put Request
+ * <li>DELETE - Delete Request
+ * </ul>
+ */
+@PublicEvolving
+public enum DynamoDbWriteRequestType {
+
+ // Note: Enums have no stable hash code across different JVMs, use toByteValue() for
+ // this purpose.
+ PUT((byte) 0),
+ DELETE((byte) 1);
+ private final byte value;
+
+ DynamoDbWriteRequestType(byte value) {
+ this.value = value;
+ }
+
+ /**
+ * Returns the byte value representation of this {@link DynamoDbWriteRequestType}. The byte
+ * value is used for serialization and deserialization.
+ *
+ * <ul>
+ * <li>"0" represents {@link #PUT}.
+ * <li>"1" represents {@link #DELETE}.
+ * </ul>
+ */
+ public byte toByteValue() {
+ return value;
+ }
+
+ /**
+ * Creates a {@link DynamoDbWriteRequestType} from the given byte value. Each {@link
+ * DynamoDbWriteRequestType} has a byte value representation.
+ *
+ * @see #toByteValue() for mapping of byte value and {@link DynamoDbWriteRequestType}.
+ */
+ public static DynamoDbWriteRequestType fromByteValue(byte value) {
+ switch (value) {
+ case 0:
+ return PUT;
+ case 1:
+ return DELETE;
+ default:
+ throw new UnsupportedOperationException(
+ "Unsupported byte value '" + value + "' for DynamoDb request type.");
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializer.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializer.java
new file mode 100644
index 0000000..039bf77
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializer.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.connector.base.sink.writer.AsyncSinkWriterStateSerializer;
+import org.apache.flink.streaming.connectors.dynamodb.util.DynamoDbSerializationUtil;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/** DynamoDb implementation {@link AsyncSinkWriterStateSerializer}. */
+@Internal
+public class DynamoDbWriterStateSerializer
+ extends AsyncSinkWriterStateSerializer<DynamoDbWriteRequest> {
+
+ /**
+ * Serializes {@link DynamoDbWriteRequest} in form of
+ * [TABLE_NAME,WRITE_REQUEST_TYPE(PUT/DELETE),WRITE_REQUEST].
+ */
+ @Override
+ protected void serializeRequestToStream(DynamoDbWriteRequest request, DataOutputStream out)
+ throws IOException {
+ DynamoDbSerializationUtil.serializeWriteRequest(request, out);
+ }
+
+ @Override
+ protected DynamoDbWriteRequest deserializeRequestFromStream(
+ long requestSize, DataInputStream in) throws IOException {
+ return DynamoDbSerializationUtil.deserializeWriteRequest(in);
+ }
+
+ @Override
+ public int getVersion() {
+ return 1;
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidConfigurationException.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidConfigurationException.java
new file mode 100644
index 0000000..f0bbae3
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidConfigurationException.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Exception is thrown if a DynamoDB configuration was invalid. */
+@PublicEvolving
+public class InvalidConfigurationException extends DynamoDbSinkException {
+ public InvalidConfigurationException(String message) {
+ super(message);
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidRequestException.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidRequestException.java
new file mode 100644
index 0000000..a6ad194
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/sink/InvalidRequestException.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.annotation.PublicEvolving;
+
+/** Exception is thrown if a DynamoDB request was invalid. */
+@PublicEvolving
+public class InvalidRequestException extends DynamoDbSinkException {
+ public InvalidRequestException(String message) {
+ super(message);
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtil.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtil.java
new file mode 100644
index 0000000..c121d26
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtil.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequest;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequestType;
+
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Serialization Utils for DynamoDb {@link AttributeValue}. This class is currently not
+ * serializable, see <a href="https://github.com/aws/aws-sdk-java-v2/issues/3143">open issue</a>
+ */
+@Internal
+public class DynamoDbSerializationUtil {
+
+ public static void serializeWriteRequest(
+ DynamoDbWriteRequest dynamoDbWriteRequest, DataOutputStream out) throws IOException {
+ out.writeByte(dynamoDbWriteRequest.getType().toByteValue());
+ Map<String, AttributeValue> item = dynamoDbWriteRequest.getItem();
+ serializeItem(item, out);
+ }
+
+ public static DynamoDbWriteRequest deserializeWriteRequest(DataInputStream in)
+ throws IOException {
+ int writeRequestType = in.read();
+ DynamoDbWriteRequestType dynamoDbWriteRequestType =
+ DynamoDbWriteRequestType.fromByteValue((byte) writeRequestType);
+ Map<String, AttributeValue> item = deserializeItem(in);
+ return DynamoDbWriteRequest.builder()
+ .setType(dynamoDbWriteRequestType)
+ .setItem(item)
+ .build();
+ }
+
+ private static void serializeItem(Map<String, AttributeValue> item, DataOutputStream out)
+ throws IOException {
+ out.writeInt(item.size());
+ for (Map.Entry<String, AttributeValue> entry : item.entrySet()) {
+ out.writeUTF(entry.getKey());
+ AttributeValue value = entry.getValue();
+ serializeAttributeValue(value, out);
+ }
+ }
+
+ private static void serializeAttributeValue(AttributeValue value, DataOutputStream out)
+ throws IOException {
+ if (value.nul() != null) {
+ out.writeByte(DynamoDbType.NULL.toByteValue());
+ } else if (value.bool() != null) {
+ out.writeByte(DynamoDbType.BOOLEAN.toByteValue());
+ out.writeBoolean(value.bool());
+ } else if (value.s() != null) {
+ out.writeByte(DynamoDbType.STRING.toByteValue());
+ out.writeUTF(value.s());
+ } else if (value.n() != null) {
+ out.writeByte(DynamoDbType.NUMBER.toByteValue());
+ out.writeUTF(value.n());
+ } else if (value.b() != null) {
+ byte[] bytes = value.b().asByteArrayUnsafe();
+ out.writeByte(DynamoDbType.BINARY.toByteValue());
+ out.writeInt(bytes.length);
+ out.write(bytes);
+ } else if (value.hasSs()) {
+ out.writeByte(DynamoDbType.STRING_SET.toByteValue());
+ out.writeInt(value.ss().size());
+ for (String s : value.ss()) {
+ out.writeUTF(s);
+ }
+ } else if (value.hasNs()) {
+ out.writeByte(DynamoDbType.NUMBER_SET.toByteValue());
+ out.writeInt(value.ns().size());
+ for (String s : value.ns()) {
+ out.writeUTF(s);
+ }
+ } else if (value.hasBs()) {
+ out.writeByte(DynamoDbType.BINARY_SET.toByteValue());
+ out.writeInt(value.bs().size());
+ for (SdkBytes sdkBytes : value.bs()) {
+ byte[] bytes = sdkBytes.asByteArrayUnsafe();
+ out.writeInt(bytes.length);
+ out.write(bytes);
+ }
+ } else if (value.hasL()) {
+ out.writeByte(DynamoDbType.LIST.toByteValue());
+ List<AttributeValue> l = value.l();
+ out.writeInt(l.size());
+ for (AttributeValue attributeValue : l) {
+ serializeAttributeValue(attributeValue, out);
+ }
+ } else if (value.hasM()) {
+ out.writeByte(DynamoDbType.MAP.toByteValue());
+ Map<String, AttributeValue> m = value.m();
+ serializeItem(m, out);
+ } else {
+ throw new IllegalArgumentException("Attribute value must not be empty: " + value);
+ }
+ }
+
+ private static Map<String, AttributeValue> deserializeItem(DataInputStream in)
+ throws IOException {
+ int size = in.readInt();
+ Map<String, AttributeValue> item = new HashMap<>(size);
+ for (int i = 0; i < size; i++) {
+ String key = in.readUTF();
+ AttributeValue attributeValue = deserializeAttributeValue(in);
+ item.put(key, attributeValue);
+ }
+ return item;
+ }
+
+ private static AttributeValue deserializeAttributeValue(DataInputStream in) throws IOException {
+ int type = in.read();
+ DynamoDbType dynamoDbType = DynamoDbType.fromByteValue((byte) type);
+ return deserializeAttributeValue(dynamoDbType, in);
+ }
+
+ private static AttributeValue deserializeAttributeValue(
+ DynamoDbType dynamoDbType, DataInputStream in) throws IOException {
+ switch (dynamoDbType) {
+ case NULL:
+ return AttributeValue.builder().nul(true).build();
+ case STRING:
+ return AttributeValue.builder().s(in.readUTF()).build();
+ case NUMBER:
+ return AttributeValue.builder().n(in.readUTF()).build();
+ case BOOLEAN:
+ return AttributeValue.builder().bool(in.readBoolean()).build();
+ case BINARY:
+ int length = in.readInt();
+ byte[] bytes = new byte[length];
+ in.read(bytes);
+ return AttributeValue.builder().b(SdkBytes.fromByteArray(bytes)).build();
+ case STRING_SET:
+ int stringSetSize = in.readInt();
+ List<String> stringSet = new ArrayList<>(stringSetSize);
+ for (int i = 0; i < stringSetSize; i++) {
+ stringSet.add(in.readUTF());
+ }
+ return AttributeValue.builder().ss(stringSet).build();
+ case NUMBER_SET:
+ int numberSetSize = in.readInt();
+ List<String> numberSet = new ArrayList<>(numberSetSize);
+ for (int i = 0; i < numberSetSize; i++) {
+ numberSet.add(in.readUTF());
+ }
+ return AttributeValue.builder().ns(numberSet).build();
+ case BINARY_SET:
+ int binarySetSize = in.readInt();
+ List<SdkBytes> byteSet = new ArrayList<>(binarySetSize);
+ for (int i = 0; i < binarySetSize; i++) {
+ int byteLength = in.readInt();
+ byte[] bs = new byte[byteLength];
+ in.read(bs);
+ byteSet.add(SdkBytes.fromByteArray(bs));
+ }
+ return AttributeValue.builder().bs(byteSet).build();
+ case LIST:
+ int listSize = in.readInt();
+ List<AttributeValue> list = new ArrayList<>(listSize);
+ for (int i = 0; i < listSize; i++) {
+ list.add(deserializeAttributeValue(in));
+ }
+ return AttributeValue.builder().l(list).build();
+ case MAP:
+ return AttributeValue.builder().m(deserializeItem(in)).build();
+ default:
+ throw new IllegalArgumentException("Unknown DynamoDbType " + dynamoDbType);
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbType.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbType.java
new file mode 100644
index 0000000..31c66b4
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbType.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+import org.apache.flink.annotation.Internal;
+
+/**
+ * enum representing the dynamodb types.
+ *
+ * <ul>
+ * <li>String
+ * <li>Number
+ * <li>Boolean
+ * <li>Null
+ * <li>Binary
+ * <li>String Set
+ * <li>Number Set
+ * <li>Binary Set
+ * <li>List
+ * <li>Map
+ * </ul>
+ */
+@Internal
+public enum DynamoDbType {
+
+ // Note: Enums have no stable hash code across different JVMs, use toByteValue() for
+ // this purpose.
+ STRING((byte) 0),
+ NUMBER((byte) 1),
+ BOOLEAN((byte) 2),
+ NULL((byte) 3),
+ BINARY((byte) 4),
+ STRING_SET((byte) 5),
+ NUMBER_SET((byte) 6),
+ BINARY_SET((byte) 7),
+ LIST((byte) 8),
+ MAP((byte) 9);
+
+ private final byte value;
+
+ DynamoDbType(byte value) {
+ this.value = value;
+ }
+
+ /**
+ * Returns the byte value representation of this {@link DynamoDbType}. The byte value is used
+ * for serialization and deserialization.
+ *
+ * <ul>
+ * <li>"0" represents {@link #STRING}.
+ * <li>"1" represents {@link #NUMBER}.
+ * <li>"2" represents {@link #BOOLEAN}.
+ * <li>"3" represents {@link #NULL}.
+ * <li>"4" represents {@link #BINARY}.
+ * <li>"5" represents {@link #STRING_SET}.
+ * <li>"6" represents {@link #NUMBER_SET}.
+ * <li>"7" represents {@link #BINARY_SET}.
+ * <li>"8" represents {@link #LIST}.
+ * <li>"9" represents {@link #MAP}.
+ * </ul>
+ */
+ public byte toByteValue() {
+ return value;
+ }
+
+ /**
+ * Creates a {@link DynamoDbType} from the given byte value. Each {@link DynamoDbType} has a
+ * byte value representation.
+ *
+ * @see #toByteValue() for mapping of byte value and {@link DynamoDbType}.
+ */
+ public static DynamoDbType fromByteValue(byte value) {
+ switch (value) {
+ case 0:
+ return STRING;
+ case 1:
+ return NUMBER;
+ case 2:
+ return BOOLEAN;
+ case 3:
+ return NULL;
+ case 4:
+ return BINARY;
+ case 5:
+ return STRING_SET;
+ case 6:
+ return NUMBER_SET;
+ case 7:
+ return BINARY_SET;
+ case 8:
+ return LIST;
+ case 9:
+ return MAP;
+ default:
+ throw new UnsupportedOperationException(
+ "Unsupported byte value '" + value + "' for DynamoDb type.");
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilder.java b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilder.java
new file mode 100644
index 0000000..239d993
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilder.java
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.streaming.connectors.dynamodb.sink.InvalidConfigurationException;
+import org.apache.flink.streaming.connectors.dynamodb.sink.InvalidRequestException;
+import org.apache.flink.util.CollectionUtil;
+
+import org.apache.commons.lang3.StringUtils;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
+
+import java.util.List;
+import java.util.Map;
+
+/** Helper to construct primary(composite) key for a DynamoDB request. */
+@Internal
+public class PrimaryKeyBuilder {
+
+ private static final String DELIMITER = "$";
+
+ private final List<String> partitionKeys;
+
+ public PrimaryKeyBuilder(List<String> partitionKeys) {
+ if (CollectionUtil.isNullOrEmpty(partitionKeys)) {
+ throw new InvalidConfigurationException(
+ "Can not construct partition key as overwriteByPartitionKeys configuration not provided");
+ }
+
+ this.partitionKeys = partitionKeys;
+ }
+
+ public String build(WriteRequest request) {
+
+ Map<String, AttributeValue> requestItems = getRequestItems(request);
+
+ StringBuilder builder = new StringBuilder();
+ for (String keyName : partitionKeys) {
+ AttributeValue keyAttribute = requestItems.get(keyName);
+
+ if (keyAttribute == null) {
+ throw new InvalidRequestException(
+ "Request "
+ + request.toString()
+ + " does not contain partition key "
+ + keyName
+ + ".");
+ }
+
+ String keyValue = getKeyValue(keyAttribute);
+
+ if (StringUtils.isBlank(keyValue)) {
+ throw new InvalidRequestException(
+ "Partition key or sort key attributes require non-empty values. Request "
+ + request.toString()
+ + " contains empty key "
+ + keyName
+ + ".");
+ }
+
+ builder.append(keyValue).append(DELIMITER);
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * Returns string value of a partition key attribute. Each primary key attribute must be defined
+ * as type String, Number, or binary as per DynamoDB specification.
+ */
+ private static String getKeyValue(AttributeValue value) {
+ StringBuilder builder = new StringBuilder();
+
+ if (value.n() != null) {
+ builder.append(value.n());
+ }
+
+ if (value.s() != null) {
+ builder.append(value.s());
+ }
+
+ if (value.b() != null) {
+ builder.append(value.b().asUtf8String());
+ }
+
+ return builder.toString();
+ }
+
+ private static Map<String, AttributeValue> getRequestItems(WriteRequest request) {
+ if (request.putRequest() != null) {
+ if (request.putRequest().hasItem()) {
+ return request.putRequest().item();
+ } else {
+ throw new InvalidRequestException(
+ "PutItemRequest " + request.toString() + " does not contain request items");
+ }
+ } else if (request.deleteRequest() != null) {
+ if (request.deleteRequest().hasKey()) {
+ return request.deleteRequest().key();
+ } else {
+ throw new InvalidRequestException(
+ "DeleteItemRequest "
+ + request.toString()
+ + " does not contain request key");
+ }
+ } else {
+ throw new InvalidRequestException("Empty write request" + request.toString());
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/main/resources/META-INF/licenses/.gitkeep b/flink-connector-dynamodb/src/main/resources/META-INF/licenses/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/flink-connector-dynamodb/src/main/resources/META-INF/services/.gitkeep b/flink-connector-dynamodb/src/main/resources/META-INF/services/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/flink-connector-dynamodb/src/main/resources/log4j2.properties b/flink-connector-dynamodb/src/main/resources/log4j2.properties
new file mode 100644
index 0000000..c64a340
--- /dev/null
+++ b/flink-connector-dynamodb/src/main/resources/log4j2.properties
@@ -0,0 +1,25 @@
+################################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License 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.
+################################################################################
+
+rootLogger.level = OFF
+rootLogger.appenderRef.console.ref = ConsoleAppender
+
+appender.console.name = ConsoleAppender
+appender.console.type = CONSOLE
+appender.console.layout.type = PatternLayout
+appender.console.layout.pattern = %d{HH:mm:ss,SSS} %-5p %-60c %x - %m%n
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/architecture/TestCodeArchitectureTest.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/architecture/TestCodeArchitectureTest.java
new file mode 100644
index 0000000..174ba43
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/architecture/TestCodeArchitectureTest.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.architecture;
+
+import org.apache.flink.architecture.common.ImportOptions;
+
+import com.tngtech.archunit.core.importer.ImportOption;
+import com.tngtech.archunit.junit.AnalyzeClasses;
+import com.tngtech.archunit.junit.ArchTest;
+import com.tngtech.archunit.junit.ArchTests;
+
+/** Architecture tests for test code. */
+@AnalyzeClasses(
+ packages = "org.apache.flink.connector.dynamodb",
+ importOptions = {
+ ImportOption.OnlyIncludeTests.class,
+ ImportOptions.ExcludeScalaImportOption.class,
+ ImportOptions.ExcludeShadedImportOption.class
+ })
+public class TestCodeArchitectureTest {
+
+ @ArchTest
+ public static final ArchTests COMMON_TESTS = ArchTests.in(TestCodeArchitectureTestBase.class);
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilderTest.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilderTest.java
new file mode 100644
index 0000000..15941ac
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkBuilderTest.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.Map;
+
+/** Tests for {@link DynamoDbSinkBuilder}. */
+public class DynamoDbSinkBuilderTest {
+
+ @Test
+ public void testCreateDynamoDbSinkBuilder() {
+ DynamoDbSink<Map<String, AttributeValue>> dynamoDbSink =
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setDestinationTableName("testTable")
+ .build();
+ Assertions.assertThat(1).isEqualTo(dynamoDbSink.getWriterStateSerializer().getVersion());
+ }
+
+ @Test
+ public void elementConverterOfSinkMustBeSetWhenBuilt() {
+ Assertions.assertThatExceptionOfType(NullPointerException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.builder()
+ .setDestinationTableName("testTable")
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "ElementConverter must be not null when initializing the AsyncSinkBase.");
+ }
+
+ @Test
+ public void destinationTableNameMustBeSetWhenBuilt() {
+ Assertions.assertThatExceptionOfType(NullPointerException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "Destination table name must be set when initializing the DynamoDB Sink.");
+ }
+
+ @Test
+ public void destinationTableNameMustBeNotEmptyWhenBuilt() {
+ Assertions.assertThatExceptionOfType(IllegalArgumentException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setDestinationTableName("")
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "Destination table name must be set when initializing the DynamoDB Sink.");
+ }
+
+ @Test
+ public void correctMaximumBatchSize() {
+ Assertions.assertThatExceptionOfType(IllegalArgumentException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setDestinationTableName("test_table")
+ .setMaxBatchSize(50)
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "DynamoDB client supports only up to 25 elements in the batch.");
+ }
+
+ @Test
+ public void maxBatchSizeInBytesThrowsNotImplemented() {
+ Assertions.assertThatExceptionOfType(InvalidConfigurationException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setDestinationTableName("test_table")
+ .setMaxBatchSizeInBytes(100)
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "Max batch size in bytes is not supported by the DynamoDB sink implementation.");
+ }
+
+ @Test
+ public void maxRecordSizeInBytesThrowsNotImplemented() {
+ Assertions.assertThatExceptionOfType(InvalidConfigurationException.class)
+ .isThrownBy(
+ () ->
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setDestinationTableName("test_table")
+ .setMaxRecordSizeInBytes(100)
+ .setFailOnError(true)
+ .build())
+ .withMessageContaining(
+ "Max record size in bytes is not supported by the DynamoDB sink implementation.");
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkITCase.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkITCase.java
new file mode 100644
index 0000000..be27ab2
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbSinkITCase.java
@@ -0,0 +1,528 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.api.common.restartstrategy.RestartStrategies;
+import org.apache.flink.connector.aws.config.AWSConfigConstants;
+import org.apache.flink.runtime.client.JobExecutionException;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.source.datagen.DataGeneratorSource;
+import org.apache.flink.streaming.api.functions.source.datagen.RandomGenerator;
+import org.apache.flink.streaming.connectors.dynamodb.testutils.DynamoDBHelpers;
+import org.apache.flink.streaming.connectors.dynamodb.testutils.DynamoDbContainer;
+import org.apache.flink.streaming.connectors.dynamodb.testutils.Item;
+import org.apache.flink.streaming.connectors.dynamodb.testutils.Items;
+import org.apache.flink.streaming.connectors.dynamodb.util.DockerImageVersions;
+import org.apache.flink.util.StringUtils;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.Network;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.net.URISyntaxException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.UUID;
+
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.AWS_ACCESS_KEY_ID;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.AWS_CREDENTIALS_PROVIDER;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.AWS_ENDPOINT;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.AWS_REGION;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.AWS_SECRET_ACCESS_KEY;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.HTTP_PROTOCOL_VERSION;
+import static org.apache.flink.connector.aws.config.AWSConfigConstants.TRUST_ALL_CERTIFICATES;
+
+/** Integration test for {@link DynamoDbSink}. */
+@Testcontainers
+public class DynamoDbSinkITCase {
+ private static final String PARTITION_KEY = "key";
+ private static final String SORT_KEY = "sort_key";
+ private static DynamoDBHelpers dynamoDBHelpers;
+ private static String testTableName;
+
+ private static StreamExecutionEnvironment env;
+
+ // shared between test methods
+ @Container
+ public static final DynamoDbContainer LOCALSTACK =
+ new DynamoDbContainer(DockerImageName.parse(DockerImageVersions.DYNAMODB))
+ .withNetwork(Network.newNetwork())
+ .withNetworkAliases("dynamodb");
+
+ @BeforeEach
+ public void setup() throws URISyntaxException {
+ testTableName = UUID.randomUUID().toString();
+ env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setRestartStrategy(RestartStrategies.noRestart());
+ env.setParallelism(1);
+
+ dynamoDBHelpers = new DynamoDBHelpers(LOCALSTACK.getHostClient());
+ }
+
+ @Test
+ public void testRandomDataSuccessfullyWritten() throws Exception {
+ int expectedNumOfElements = 10;
+ int bytesPerMessage = 10;
+ new Scenario(getRandomDataGenerator(bytesPerMessage, expectedNumOfElements))
+ .withTableName(testTableName)
+ .withExpectedElements(expectedNumOfElements)
+ .runScenario();
+ }
+
+ @Test
+ public void veryLargeMessagesFailsGracefullyWhenRejectedByDynamoDb() throws Exception {
+ Assertions.assertThatExceptionOfType(JobExecutionException.class)
+ .isThrownBy(
+ () ->
+ // 500 * 1000 bytes is more than DynamoDB allows for a single record
+ new Scenario(getRandomDataGenerator(500 * 1000, 5))
+ .withExpectedElements(5)
+ .withTableName(testTableName)
+ .runScenario())
+ .havingCause()
+ .havingCause()
+ .havingCause()
+ .withMessageContaining("Item size has exceeded the maximum allowed size");
+ }
+
+ @Test
+ public void nonExistentTableNameShouldResultInFailureWhenFailOnErrorIsTrue() throws Exception {
+ testJobFatalFailureTerminatesCorrectlyWithFailOnErrorFlagSetTo(true);
+ }
+
+ @Test
+ public void nonExistentTableNameShouldResultInFailureWhenFailOnErrorIsFalse() {
+ testJobFatalFailureTerminatesCorrectlyWithFailOnErrorFlagSetTo(false);
+ }
+
+ private void testJobFatalFailureTerminatesCorrectlyWithFailOnErrorFlagSetTo(
+ boolean failOnError) {
+ List<Map<String, AttributeValue>> items =
+ Items.builder().item(Item.builder().attr("1", "1").build()).build();
+ Assertions.assertThatExceptionOfType(JobExecutionException.class)
+ .isThrownBy(
+ () ->
+ new Scenario(env.fromCollection(items))
+ .withTableName("NonExistentTableName")
+ .withFailOnError(failOnError)
+ .runScenario())
+ .havingCause()
+ .havingCause()
+ .withMessageContaining("Encountered non-recoverable exception");
+ }
+
+ @Test
+ void badRegionShouldResultInFailureWhenInFailOnErrorIsOn() {
+ badRegionShouldResultInFailureWhenInFailOnErrorIs(true);
+ }
+
+ @Test
+ void badRegionShouldResultInFailureWhenInFailOnErrorIsOff() {
+ badRegionShouldResultInFailureWhenInFailOnErrorIs(false);
+ }
+
+ private void badRegionShouldResultInFailureWhenInFailOnErrorIs(boolean failOnError) {
+ Properties properties = getDefaultProperties();
+ properties.setProperty(AWS_REGION, "some-bad-region");
+
+ assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ failOnError, properties, "Invalid AWS region");
+ }
+
+ @Test
+ void missingRegionShouldResultInFailureWhenInFailOnErrorIsOn() {
+ missingRegionShouldResultInFailureWhenInFailOnErrorIs(true);
+ }
+
+ @Test
+ void missingRegionShouldResultInFailureWhenInFailOnErrorIsOff() {
+ missingRegionShouldResultInFailureWhenInFailOnErrorIs(false);
+ }
+
+ private void missingRegionShouldResultInFailureWhenInFailOnErrorIs(boolean failOnError) {
+ Properties properties = getDefaultProperties();
+ properties.remove(AWS_REGION);
+ assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ failOnError, properties, "region must not be null.");
+ }
+
+ @Test
+ void noURIEndpointShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noURIEndpointShouldResultInFailureWhenInFailOnErrorIs(true);
+ }
+
+ @Test
+ void noURIEndpointShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noURIEndpointShouldResultInFailureWhenInFailOnErrorIs(false);
+ }
+
+ private void noURIEndpointShouldResultInFailureWhenInFailOnErrorIs(boolean failOnError) {
+ Properties properties = getDefaultProperties();
+ properties.setProperty(AWS_ENDPOINT, "bad-endpoint-no-uri");
+ assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ failOnError, properties, "The URI scheme of endpointOverride must not be null.");
+ }
+
+ @Test
+ void badEndpointShouldResultInFailureWhenInFailOnErrorIsOn() {
+ badEndpointShouldResultInFailureWhenInFailOnErrorIs(true);
+ }
+
+ @Test
+ void badEndpointShouldResultInFailureWhenInFailOnErrorIsOff() {
+ badEndpointShouldResultInFailureWhenInFailOnErrorIs(false);
+ }
+
+ private void badEndpointShouldResultInFailureWhenInFailOnErrorIs(boolean failOnError) {
+ Properties properties = getDefaultProperties();
+ properties.setProperty(AWS_ENDPOINT, "https://bad-endpoint-with-uri");
+ assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ failOnError,
+ properties,
+ "UnknownHostException when attempting to interact with a service.");
+ }
+
+ @Test
+ void envVarWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ true,
+ AWSConfigConstants.CredentialProvider.ENV_VAR.toString(),
+ "Access key must be specified either via environment variable");
+ }
+
+ @Test
+ void envVarWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ false,
+ AWSConfigConstants.CredentialProvider.ENV_VAR.toString(),
+ "Access key must be specified either via environment variable");
+ }
+
+ @Test
+ void sysPropWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ true,
+ AWSConfigConstants.CredentialProvider.SYS_PROP.toString(),
+ "Unable to load credentials from system settings");
+ }
+
+ @Test
+ void sysPropWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ false,
+ AWSConfigConstants.CredentialProvider.SYS_PROP.toString(),
+ "Unable to load credentials from system settings");
+ }
+
+ @Test
+ void basicWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ true,
+ AWSConfigConstants.CredentialProvider.BASIC.toString(),
+ "Please set values for AWS Access Key ID ('aws.credentials.provider.basic.accesskeyid') and Secret Key ('aws.credentials.provider.basic.secretkey') when using the BASIC AWS credential provider type.");
+ }
+
+ @Test
+ void basicWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ false,
+ AWSConfigConstants.CredentialProvider.BASIC.toString(),
+ "Please set values for AWS Access Key ID ('aws.credentials.provider.basic.accesskeyid') and Secret Key ('aws.credentials.provider.basic.secretkey') when using the BASIC AWS credential provider type.");
+ }
+
+ @Test
+ void webIdentityTokenWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ true,
+ AWSConfigConstants.CredentialProvider.WEB_IDENTITY_TOKEN.toString(),
+ "Either the environment variable AWS_WEB_IDENTITY_TOKEN_FILE or the javaproperty aws.webIdentityTokenFile must be set");
+ }
+
+ @Test
+ void webIdentityTokenWithNoCredentialsShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ false,
+ AWSConfigConstants.CredentialProvider.WEB_IDENTITY_TOKEN.toString(),
+ "Either the environment variable AWS_WEB_IDENTITY_TOKEN_FILE or the javaproperty aws.webIdentityTokenFile must be set");
+ }
+
+ @Test
+ void wrongCredentialProviderNameShouldResultInFailureWhenInFailOnErrorIsOn() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ true, "WRONG", "Invalid AWS Credential Provider Type");
+ }
+
+ @Test
+ void wrongCredentialProviderNameShouldResultInFailureWhenInFailOnErrorIsOff() {
+ noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ false, "WRONG", "Invalid AWS Credential Provider Type");
+ }
+
+ private void noCredentialsProvidedAndCredentialsProviderSpecifiedShouldResultInFailure(
+ boolean failOnError, String credentialsProvider, String expectedMessage) {
+ assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ failOnError,
+ getDefaultPropertiesWithoutCredentialsSetAndCredentialProvider(credentialsProvider),
+ expectedMessage);
+ }
+
+ private void assertRunWithPropertiesAndSinkShouldFailWithExceptionOfType(
+ boolean failOnError, Properties properties, String expectedMessage) {
+ Assertions.assertThatExceptionOfType(JobExecutionException.class)
+ .isThrownBy(
+ () ->
+ new Scenario(getRandomDataGenerator(10, 1))
+ .withTableName(testTableName)
+ .withFailOnError(failOnError)
+ .withClientProperties(properties)
+ .runScenario())
+ .havingCause()
+ .havingCause()
+ .withMessageContaining(expectedMessage);
+ }
+
+ @Test
+ public void batchRequestFailsBecauseNoDeduplicationConfiguration() {
+ Assertions.assertThatExceptionOfType(JobExecutionException.class)
+ .isThrownBy(
+ () ->
+ new Scenario(
+ env.fromCollection(
+ getItemsWithDuplicatedCompositeKey()))
+ .withTableName(testTableName)
+ .withBufferMaxTimeMS(60 * 1000)
+ .withExpectedElements(1)
+ .withMaxInflightReqs(1)
+ .runScenario())
+ .havingCause()
+ .havingCause()
+ .havingCause()
+ .withMessageContaining("Provided list of item keys contains duplicates");
+ }
+
+ @Test
+ public void deduplicatesOnPartitionKey() throws Exception {
+ new Scenario(env.fromCollection(getItemsWithDuplicatedPartitionKey()))
+ .withTableName(testTableName)
+ .withOverwriteByPartitionKeys(ImmutableList.of(PARTITION_KEY))
+ .withBufferMaxTimeMS(60 * 1000)
+ .withExpectedElements(1)
+ .withMaxInflightReqs(1)
+ .runScenario();
+ }
+
+ @Test
+ public void deduplicatesOnCompositeKeyAndNewerItemTakesPrecedence() throws Exception {
+ new Scenario(env.fromCollection(getItemsWithDuplicatedCompositeKey()))
+ .withTableName(testTableName)
+ .withOverwriteByPartitionKeys(ImmutableList.of(PARTITION_KEY, SORT_KEY))
+ .withBufferMaxTimeMS(60 * 1000)
+ // more than one in-flight request may cause a race condition
+ // where the first request to complete will take precedence
+ .withMaxInflightReqs(1)
+ .withExpectedElements(1)
+ .withExpectedAttribute("payload", "value3")
+ .runScenario();
+ }
+
+ private List<Map<String, AttributeValue>> getItemsWithDuplicatedCompositeKey() {
+ return Items.builder()
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "2")
+ .attr(SORT_KEY, "1")
+ .attr("payload", "value1")
+ .build())
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "2")
+ .attr(SORT_KEY, "1")
+ .attr("payload", "value2")
+ .build())
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "2")
+ .attr(SORT_KEY, "1")
+ .attr("payload", "value3")
+ .build())
+ .build();
+ }
+
+ private List<Map<String, AttributeValue>> getItemsWithDuplicatedPartitionKey() {
+ return Items.builder()
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "1")
+ .attr(SORT_KEY, "1")
+ .attr("payload", "value1")
+ .build())
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "1")
+ .attr(SORT_KEY, "2")
+ .attr("payload", "value2")
+ .build())
+ .item(
+ Item.builder()
+ .attr(PARTITION_KEY, "1")
+ .attr(SORT_KEY, "3")
+ .attr("payload", "value3")
+ .build())
+ .build();
+ }
+
+ private DataStream<Map<String, AttributeValue>> getRandomDataGenerator(
+ int sizeOfMessageBytes, long numberOfElementsToSend) {
+ return env.addSource(
+ new DataGeneratorSource<>(
+ RandomGenerator.stringGenerator(sizeOfMessageBytes),
+ 100,
+ numberOfElementsToSend))
+ .returns(String.class)
+ .map(new TestRequestMapper(PARTITION_KEY, SORT_KEY));
+ }
+
+ private Properties getDefaultPropertiesWithoutCredentialsSetAndCredentialProvider(
+ String credentialsProvider) {
+ Properties properties = getDefaultProperties();
+ properties.setProperty(AWS_CREDENTIALS_PROVIDER, credentialsProvider);
+ properties.remove(AWS_SECRET_ACCESS_KEY);
+ properties.remove(AWS_ACCESS_KEY_ID);
+ return properties;
+ }
+
+ private Properties getDefaultProperties() {
+ Properties properties = new Properties();
+ properties.setProperty(AWS_ENDPOINT, LOCALSTACK.getHostEndpointUrl());
+ properties.setProperty(AWS_ACCESS_KEY_ID, LOCALSTACK.getAccessKey());
+ properties.setProperty(AWS_SECRET_ACCESS_KEY, LOCALSTACK.getSecretKey());
+ properties.setProperty(AWS_REGION, LOCALSTACK.getRegion().toString());
+ properties.setProperty(TRUST_ALL_CERTIFICATES, "true");
+ properties.setProperty(HTTP_PROTOCOL_VERSION, "HTTP1_1");
+ return properties;
+ }
+
+ private class Scenario {
+
+ private final DataStream<Map<String, AttributeValue>> dataGenerator;
+
+ private int bufferMaxTimeMS = 1000;
+ private int maxInflightReqs = 50;
+ private int maxBatchSize = 25;
+ private int expectedElements = 50;
+ private boolean failOnError = false;
+ private String tableName;
+ private String expectedAttributeName;
+ private String expectedAttributeValue;
+ private Properties properties = DynamoDbSinkITCase.this.getDefaultProperties();
+
+ private final List<String> deduplicateOnKeys = new ArrayList<>();
+
+ public Scenario(DataStream<Map<String, AttributeValue>> dataGenerator) {
+ this.dataGenerator = dataGenerator;
+ }
+
+ public void runScenario() throws Exception {
+ dynamoDBHelpers.createTable(testTableName, PARTITION_KEY, SORT_KEY);
+
+ DynamoDbSink<Map<String, AttributeValue>> dynamoDbSink =
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setMaxTimeInBufferMS(bufferMaxTimeMS)
+ .setMaxInFlightRequests(maxInflightReqs)
+ .setMaxBatchSize(maxBatchSize)
+ .setFailOnError(failOnError)
+ .setMaxBufferedRequests(1000)
+ .setDestinationTableName(tableName)
+ .setOverwriteByPartitionKeys(deduplicateOnKeys)
+ .setDynamoDbProperties(properties)
+ .build();
+
+ dataGenerator.sinkTo(dynamoDbSink);
+
+ env.execute("DynamoDbSink Async Sink Example Program");
+
+ Assertions.assertThat(dynamoDBHelpers.getItemsCount(tableName))
+ .isEqualTo(expectedElements);
+
+ if (!StringUtils.isNullOrWhitespaceOnly(expectedAttributeName)) {
+ Assertions.assertThat(
+ dynamoDBHelpers.containsAttributeValue(
+ tableName, expectedAttributeName, expectedAttributeValue))
+ .isTrue();
+ }
+ }
+
+ public Scenario withBufferMaxTimeMS(int bufferMaxTimeMS) {
+ this.bufferMaxTimeMS = bufferMaxTimeMS;
+ return this;
+ }
+
+ public Scenario withMaxInflightReqs(int maxInflightReqs) {
+ this.maxInflightReqs = maxInflightReqs;
+ return this;
+ }
+
+ public Scenario withMaxBatchSize(int maxBatchSize) {
+ this.maxBatchSize = maxBatchSize;
+ return this;
+ }
+
+ public Scenario withExpectedElements(int expectedElements) {
+ this.expectedElements = expectedElements;
+ return this;
+ }
+
+ public Scenario withExpectedAttribute(String name, String value) {
+ this.expectedAttributeName = name;
+ this.expectedAttributeValue = value;
+ return this;
+ }
+
+ public Scenario withFailOnError(boolean failOnError) {
+ this.failOnError = failOnError;
+ return this;
+ }
+
+ public Scenario withTableName(String tableName) {
+ this.tableName = tableName;
+ return this;
+ }
+
+ public Scenario withOverwriteByPartitionKeys(List<String> deduplicateOnKeys) {
+ this.deduplicateOnKeys.addAll(deduplicateOnKeys);
+ return this;
+ }
+
+ public Scenario withClientProperties(Properties properties) {
+ this.properties = properties;
+ return this;
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializerTest.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializerTest.java
new file mode 100644
index 0000000..55e9102
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/DynamoDbWriterStateSerializerTest.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.connector.base.sink.writer.BufferedRequestState;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableMap;
+
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import static org.apache.flink.connector.base.sink.writer.AsyncSinkWriterTestUtils.assertThatBufferStatesAreEqual;
+import static org.apache.flink.connector.base.sink.writer.AsyncSinkWriterTestUtils.getTestState;
+
+/**
+ * Tests for serializing and deserialzing a collection of {@link DynamoDbWriteRequest} with {@link
+ * DynamoDbWriterStateSerializer}.
+ */
+public class DynamoDbWriterStateSerializerTest {
+
+ private static final ElementConverter<String, DynamoDbWriteRequest> ELEMENT_CONVERTER =
+ (element, context) ->
+ DynamoDbWriteRequest.builder()
+ .setType(DynamoDbWriteRequestType.PUT)
+ .setItem(
+ ImmutableMap.of(
+ "key", AttributeValue.builder().s(element).build()))
+ .build();
+
+ @Test
+ public void testSerializeAndDeserialize() throws IOException {
+ BufferedRequestState<DynamoDbWriteRequest> expectedState =
+ getTestState(ELEMENT_CONVERTER, this::getRequestSize);
+
+ DynamoDbWriterStateSerializer serializer = new DynamoDbWriterStateSerializer();
+ BufferedRequestState<DynamoDbWriteRequest> actualState =
+ serializer.deserialize(1, serializer.serialize(expectedState));
+
+ assertThatBufferStatesAreEqual(actualState, expectedState);
+ }
+
+ private int getRequestSize(DynamoDbWriteRequest requestEntry) {
+ return requestEntry.getItem().toString().getBytes(StandardCharsets.UTF_8).length;
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestDynamoDbElementConverter.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestDynamoDbElementConverter.java
new file mode 100644
index 0000000..8fd8d13
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestDynamoDbElementConverter.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.Map;
+
+/** DynamoDB element converter test implementation. */
+public class TestDynamoDbElementConverter
+ implements ElementConverter<Map<String, AttributeValue>, DynamoDbWriteRequest> {
+
+ @Override
+ public DynamoDbWriteRequest apply(
+ Map<String, AttributeValue> elements, SinkWriter.Context context) {
+ return DynamoDbWriteRequest.builder()
+ .setType(DynamoDbWriteRequestType.PUT)
+ .setItem(elements)
+ .build();
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestRequestMapper.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestRequestMapper.java
new file mode 100644
index 0000000..445ac05
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/TestRequestMapper.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink;
+
+import org.apache.flink.api.common.functions.RichMapFunction;
+
+import org.apache.commons.math3.random.RandomDataGenerator;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** Mapper function to test DynamoDB sync implementation. */
+public class TestRequestMapper extends RichMapFunction<String, Map<String, AttributeValue>> {
+
+ private final String partitionKey;
+ private final String sortKey;
+ private final RandomDataGenerator random = new RandomDataGenerator();
+
+ public TestRequestMapper(String partitionKey, String sortKey) {
+ this.partitionKey = partitionKey;
+ this.sortKey = sortKey;
+ }
+
+ @Override
+ public Map<String, AttributeValue> map(String data) throws Exception {
+ final Map<String, AttributeValue> item = new HashMap<>();
+ item.put(partitionKey, AttributeValue.builder().s(this.random.nextHexString(5)).build());
+ item.put(sortKey, AttributeValue.builder().s(this.random.nextHexString(5)).build());
+ item.put("payload", AttributeValue.builder().s(data).build());
+ return item;
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/examples/SinkIntoDynamoDb.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/examples/SinkIntoDynamoDb.java
new file mode 100644
index 0000000..53035fd
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/sink/examples/SinkIntoDynamoDb.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.sink.examples;
+
+import org.apache.flink.api.common.functions.RichMapFunction;
+import org.apache.flink.api.connector.sink2.SinkWriter;
+import org.apache.flink.connector.aws.config.AWSConfigConstants;
+import org.apache.flink.connector.base.sink.writer.ElementConverter;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbSink;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequest;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequestType;
+
+import org.apache.commons.math3.random.RandomDataGenerator;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * An example application demonstrating how to use the {@link DynamoDbSink} to sink into DynamoDb.
+ */
+public class SinkIntoDynamoDb {
+
+ public static void main(String[] args) throws Exception {
+ final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.enableCheckpointing(10_000);
+
+ DataStream<String> fromGen =
+ env.fromSequence(1, 10_000_000L).map(Object::toString).returns(String.class);
+
+ Properties sinkProperties = new Properties();
+ sinkProperties.put(AWSConfigConstants.AWS_REGION, "your-region-here");
+
+ DynamoDbSink<Map<String, AttributeValue>> dynamoDbSink =
+ DynamoDbSink.<Map<String, AttributeValue>>builder()
+ .setDestinationTableName("my-dynamodb-table")
+ .setElementConverter(new TestDynamoDbElementConverter())
+ .setMaxBatchSize(20)
+ .setDynamoDbProperties(sinkProperties)
+ .build();
+
+ fromGen.map(new TestRequestMapper()).sinkTo(dynamoDbSink);
+
+ env.execute("DynamoDb Async Sink Example Program");
+ }
+
+ /** Example DynamoDB request attributes mapper. */
+ public static class TestRequestMapper
+ extends RichMapFunction<String, Map<String, AttributeValue>> {
+ private final RandomDataGenerator random = new RandomDataGenerator();
+
+ @Override
+ public Map<String, AttributeValue> map(String data) throws Exception {
+ final Map<String, AttributeValue> item = new HashMap<>();
+ item.put(
+ "partition_key",
+ AttributeValue.builder().s(this.random.nextHexString(5)).build());
+ item.put("sort_key", AttributeValue.builder().s(this.random.nextHexString(5)).build());
+ item.put("payload", AttributeValue.builder().s(data).build());
+ return item;
+ }
+ }
+
+ /** Example DynamoDB element converter. */
+ public static class TestDynamoDbElementConverter
+ implements ElementConverter<Map<String, AttributeValue>, DynamoDbWriteRequest> {
+
+ @Override
+ public DynamoDbWriteRequest apply(
+ Map<String, AttributeValue> elements, SinkWriter.Context context) {
+ return DynamoDbWriteRequest.builder()
+ .setType(DynamoDbWriteRequestType.PUT)
+ .setItem(elements)
+ .build();
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDBHelpers.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDBHelpers.java
new file mode 100644
index 0000000..a4f9dc1
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDBHelpers.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.testutils;
+
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
+import software.amazon.awssdk.services.dynamodb.model.KeyType;
+import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
+import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
+import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter;
+
+import java.util.Collections;
+import java.util.concurrent.ExecutionException;
+
+/** Helper methods to call dynamoDB service. */
+public class DynamoDBHelpers {
+ private final DynamoDbAsyncClient client;
+
+ public DynamoDBHelpers(DynamoDbAsyncClient hostClient) {
+ this.client = hostClient;
+ }
+
+ public void createTable(String tableName, String partitionKey, String sortKey)
+ throws ExecutionException, InterruptedException {
+ client.createTable(
+ CreateTableRequest.builder()
+ .tableName(tableName)
+ .attributeDefinitions(
+ AttributeDefinition.builder()
+ .attributeName(partitionKey)
+ .attributeType(ScalarAttributeType.S)
+ .build(),
+ AttributeDefinition.builder()
+ .attributeName(sortKey)
+ .attributeType(ScalarAttributeType.S)
+ .build())
+ .keySchema(
+ KeySchemaElement.builder()
+ .attributeName(partitionKey)
+ .keyType(KeyType.HASH)
+ .build(),
+ KeySchemaElement.builder()
+ .attributeName(sortKey)
+ .keyType(KeyType.RANGE)
+ .build())
+ .provisionedThroughput(
+ ProvisionedThroughput.builder()
+ .readCapacityUnits(1000L)
+ .writeCapacityUnits(1000L)
+ .build())
+ .build());
+
+ DynamoDbAsyncWaiter waiter = client.waiter();
+ waiter.waitUntilTableExists(r -> r.tableName(tableName)).get();
+ }
+
+ public int getItemsCount(String tableName) throws ExecutionException, InterruptedException {
+ return client.scan(ScanRequest.builder().tableName(tableName).build()).get().count();
+ }
+
+ public boolean containsAttributeValue(
+ String tableName, String attributeName, String attributeValue)
+ throws ExecutionException, InterruptedException {
+ ScanRequest containsRequest =
+ ScanRequest.builder()
+ .expressionAttributeNames(Collections.singletonMap("#A", attributeName))
+ .expressionAttributeValues(
+ Collections.singletonMap(
+ ":val", AttributeValue.builder().s(attributeValue).build()))
+ .filterExpression("#A = :val")
+ .tableName(tableName)
+ .build();
+ return client.scan(containsRequest).get().count() > 0;
+ }
+
+ public void deleteTable(String tableName) {
+ client.deleteTable(DeleteTableRequest.builder().tableName(tableName).build());
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDbContainer.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDbContainer.java
new file mode 100644
index 0000000..e0ae78c
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/DynamoDbContainer.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.testutils;
+
+import org.apache.flink.connector.aws.config.AWSConfigConstants;
+
+import org.rnorth.ducttape.ratelimits.RateLimiter;
+import org.rnorth.ducttape.ratelimits.RateLimiterBuilder;
+import org.rnorth.ducttape.unreliables.Unreliables;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;
+import org.testcontainers.utility.DockerImageName;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.core.SdkSystemSetting;
+import software.amazon.awssdk.http.SdkHttpConfigurationOption;
+import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
+import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
+import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
+import software.amazon.awssdk.utils.AttributeMap;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Properties;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+/** A testcontainer based on DynamoDb. */
+public class DynamoDbContainer extends GenericContainer<DynamoDbContainer> {
+ private static final String ACCESS_KEY = "access key";
+ private static final String SECRET_KEY = "secret key";
+ private static final int PORT = 8000;
+ private static final Region REGION = Region.US_EAST_1;
+ private static final String URL_FORMAT = "http://%s:%s";
+
+ public DynamoDbContainer(DockerImageName imageName) {
+ super(imageName);
+
+ System.setProperty(SdkSystemSetting.CBOR_ENABLED.property(), "false");
+
+ withExposedPorts(PORT);
+ waitingFor(new DynamoDBWaiterStrategy());
+ }
+
+ /** Returns the endpoint url to access the container from outside the docker network. */
+ public String getContainerEndpointUrl() {
+ return String.format(URL_FORMAT, getContainerIpAddress(), getMappedPort(PORT));
+ }
+
+ /** Returns the endpoint url to access the host from inside the docker network. */
+ public String getHostEndpointUrl() {
+ return String.format(URL_FORMAT, getHost(), getMappedPort(PORT));
+ }
+
+ public String getAccessKey() {
+ return ACCESS_KEY;
+ }
+
+ public String getSecretKey() {
+ return SECRET_KEY;
+ }
+
+ public Region getRegion() {
+ return REGION;
+ }
+
+ /** Returns the properties to access the container from outside the docker network. */
+ public Properties getContainerProperties() {
+ return getProperties(getContainerEndpointUrl());
+ }
+
+ /** Returns the properties to access the host from inside the docker network. */
+ public Properties getHostProperties() {
+ return getProperties(getHostEndpointUrl());
+ }
+
+ /** Returns the client to access the container from outside the docker network. */
+ public DynamoDbAsyncClient getContainerClient() throws URISyntaxException {
+ return getClient(getContainerEndpointUrl());
+ }
+
+ /** Returns the client to access the host from inside the docker network. */
+ public DynamoDbAsyncClient getHostClient() throws URISyntaxException {
+ return getClient(getHostEndpointUrl());
+ }
+
+ public DynamoDbAsyncClient getClient(String endPoint) throws URISyntaxException {
+ return DynamoDbAsyncClient.builder()
+ .endpointOverride(new URI(endPoint))
+ .region(REGION)
+ .credentialsProvider(
+ () -> AwsBasicCredentials.create(getAccessKey(), getSecretKey()))
+ .httpClient(buildSdkAsyncHttpClient())
+ .build();
+ }
+
+ private Properties getProperties(String endpointUrl) {
+ Properties config = new Properties();
+ config.setProperty(AWSConfigConstants.AWS_REGION, REGION.toString());
+ config.setProperty(AWSConfigConstants.AWS_ENDPOINT, endpointUrl);
+ config.setProperty(AWSConfigConstants.AWS_ACCESS_KEY_ID, getAccessKey());
+ config.setProperty(AWSConfigConstants.AWS_SECRET_ACCESS_KEY, getSecretKey());
+ return config;
+ }
+
+ private class DynamoDBWaiterStrategy extends AbstractWaitStrategy {
+ private static final int TRANSACTIONS_PER_SECOND = 1;
+
+ private final RateLimiter rateLimiter =
+ RateLimiterBuilder.newBuilder()
+ .withRate(TRANSACTIONS_PER_SECOND, SECONDS)
+ .withConstantThroughput()
+ .build();
+
+ @Override
+ protected void waitUntilReady() {
+ try {
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+
+ retryUntilSuccessRunner(this::list);
+ }
+
+ protected <T> void retryUntilSuccessRunner(final Callable<T> lambda) {
+ Unreliables.retryUntilSuccess(
+ (int) startupTimeout.getSeconds(),
+ SECONDS,
+ () -> rateLimiter.getWhenReady(lambda));
+ }
+
+ private ListTablesResponse list()
+ throws URISyntaxException, ExecutionException, InterruptedException {
+ return getContainerClient().listTables().get();
+ }
+ }
+
+ private SdkAsyncHttpClient buildSdkAsyncHttpClient() {
+ return NettyNioAsyncHttpClient.builder()
+ .buildWithDefaults(
+ AttributeMap.builder()
+ .put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, true)
+ .build());
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Item.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Item.java
new file mode 100644
index 0000000..27d148e
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Item.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.testutils;
+
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/** DynamoDB item container. */
+public class Item {
+
+ public static Item.ItemBuilder builder() {
+ return new Item.ItemBuilder();
+ }
+
+ /** Builder to constrict DynamoDB item. */
+ public static final class ItemBuilder {
+ Map<String, AttributeValue> item = new HashMap<>();
+
+ public Item.ItemBuilder attr(String name, String value) {
+ item.put(name, AttributeValue.builder().s(value).build());
+ return this;
+ }
+
+ public Map<String, AttributeValue> build() {
+ return item;
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Items.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Items.java
new file mode 100644
index 0000000..fa2adbc
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/testutils/Items.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.testutils;
+
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/** Container for DynamoDB items. */
+public class Items {
+
+ public static ItemsBuilder builder() {
+ return new Items.ItemsBuilder();
+ }
+
+ /** Builder to constrict DynamoDB items. */
+ public static final class ItemsBuilder {
+ private final List<Map<String, AttributeValue>> items = new ArrayList<>();
+
+ public ItemsBuilder item(Map<String, AttributeValue> attributes) {
+ items.add(attributes);
+ return this;
+ }
+
+ public List<Map<String, AttributeValue>> build() {
+ return items;
+ }
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DockerImageVersions.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DockerImageVersions.java
new file mode 100644
index 0000000..6b7e29e
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DockerImageVersions.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+/**
+ * Utility class for defining the image names and versions of Docker containers used during the Java
+ * tests. The names/versions are centralised here in order to make testing version updates easier,
+ * as well as to provide a central file to use as a key when caching testing Docker files.
+ *
+ * <p>In order for an image to be cached it must be added to {@code
+ * cache_docker_images.sh#DOCKER_IMAGE_CACHE_PATTERN}.
+ */
+public class DockerImageVersions {
+
+ public static final String DYNAMODB = "amazon/dynamodb-local:1.16.0";
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtilTest.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtilTest.java
new file mode 100644
index 0000000..53434d8
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/DynamoDbSerializationUtilTest.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequest;
+import org.apache.flink.streaming.connectors.dynamodb.sink.DynamoDbWriteRequestType;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableMap;
+
+import org.junit.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Tests for {@link DynamoDbSerializationUtil}. */
+public class DynamoDbSerializationUtilTest {
+
+ @Test
+ public void testPutItemSerializeDeserialize() throws IOException {
+ final Map<String, AttributeValue> item = new HashMap<>();
+ item.put("string", AttributeValue.builder().s("string").build());
+ item.put("number", AttributeValue.builder().s("123.4212").build());
+ item.put(
+ "binary",
+ AttributeValue.builder().b(SdkBytes.fromByteArray(new byte[] {1, 2, 3})).build());
+ item.put("null", AttributeValue.builder().nul(true).build());
+ item.put("boolean", AttributeValue.builder().bool(true).build());
+ item.put("stringSet", AttributeValue.builder().ss("s1", "s2").build());
+ item.put("numberSet", AttributeValue.builder().ns("123.1231", "123123").build());
+ item.put(
+ "binarySet",
+ AttributeValue.builder()
+ .bs(
+ SdkBytes.fromByteArray(new byte[] {1, 2, 3}),
+ SdkBytes.fromByteArray(new byte[] {4, 5, 6}))
+ .build());
+ item.put(
+ "list",
+ AttributeValue.builder()
+ .l(
+ AttributeValue.builder().s("s1").build(),
+ AttributeValue.builder().s("s2").build())
+ .build());
+ item.put(
+ "map",
+ AttributeValue.builder()
+ .m(
+ ImmutableMap.of(
+ "key1", AttributeValue.builder().s("string").build(),
+ "key2", AttributeValue.builder().n("12345").build(),
+ "binary",
+ AttributeValue.builder()
+ .b(
+ SdkBytes.fromByteArray(
+ new byte[] {1, 2, 3}))
+ .build(),
+ "null", AttributeValue.builder().nul(true).build()))
+ .build());
+ DynamoDbWriteRequest dynamoDbWriteRequest =
+ DynamoDbWriteRequest.builder()
+ .setItem(item)
+ .setType(DynamoDbWriteRequestType.PUT)
+ .build();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(outputStream);
+ DynamoDbSerializationUtil.serializeWriteRequest(dynamoDbWriteRequest, out);
+ outputStream.close();
+ out.close();
+ InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+ DataInputStream dataInputStream = new DataInputStream(inputStream);
+ DynamoDbWriteRequest deserializedWriteRequest =
+ DynamoDbSerializationUtil.deserializeWriteRequest(dataInputStream);
+ inputStream.close();
+ assertThat(deserializedWriteRequest).isEqualTo(dynamoDbWriteRequest);
+ }
+
+ @Test
+ public void testDeleteItemSerializeDeserialize() throws IOException {
+ final Map<String, AttributeValue> key = new HashMap<>();
+ key.put("string", AttributeValue.builder().s("string").build());
+ key.put("number", AttributeValue.builder().s("123.4212").build());
+ DynamoDbWriteRequest dynamoDbWriteRequest =
+ DynamoDbWriteRequest.builder()
+ .setItem(key)
+ .setType(DynamoDbWriteRequestType.DELETE)
+ .build();
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ DataOutputStream out = new DataOutputStream(outputStream);
+ DynamoDbSerializationUtil.serializeWriteRequest(dynamoDbWriteRequest, out);
+ outputStream.close();
+ out.close();
+ InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
+ DataInputStream dataInputStream = new DataInputStream(inputStream);
+ DynamoDbWriteRequest deserializedWriteRequest =
+ DynamoDbSerializationUtil.deserializeWriteRequest(dataInputStream);
+ inputStream.close();
+ assertThat(deserializedWriteRequest).isEqualTo(dynamoDbWriteRequest);
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilderTest.java b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilderTest.java
new file mode 100644
index 0000000..ff152f1
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/java/org/apache/flink/streaming/connectors/dynamodb/util/PrimaryKeyBuilderTest.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License 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 org.apache.flink.streaming.connectors.dynamodb.util;
+
+import org.apache.flink.streaming.connectors.dynamodb.sink.InvalidRequestException;
+
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableList;
+import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableMap;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
+import software.amazon.awssdk.services.dynamodb.model.PutRequest;
+import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+/** Unit tests for {@link PrimaryKeyBuilder}. */
+public class PrimaryKeyBuilderTest {
+
+ private static final String PARTITION_KEY_NAME = "part_key_name";
+ private static final String SORT_KEY_NAME = "sort_key_name";
+
+ private ImmutableMap<String, AttributeValue> createItemValues() {
+ return ImmutableMap.of(
+ PARTITION_KEY_NAME,
+ AttributeValue.builder()
+ .s("123")
+ .n("456")
+ .b(SdkBytes.fromString("789", StandardCharsets.UTF_8))
+ .build(),
+ SORT_KEY_NAME,
+ AttributeValue.builder().s("101112").build(),
+ "some_item",
+ AttributeValue.builder().bool(false).build());
+ }
+
+ public WriteRequest createPutItemRequest(Map<String, AttributeValue> itemValues) {
+ return WriteRequest.builder()
+ .putRequest(PutRequest.builder().item(itemValues).build())
+ .build();
+ }
+
+ public WriteRequest createDeleteItemRequest(Map<String, AttributeValue> itemValues) {
+ return WriteRequest.builder()
+ .deleteRequest(DeleteRequest.builder().key(itemValues).build())
+ .build();
+ }
+
+ @Test
+ public void testPrimaryKeyDelimited() {
+ WriteRequest putRequestOne =
+ createPutItemRequest(
+ ImmutableMap.of(
+ PARTITION_KEY_NAME,
+ AttributeValue.builder().s("ab").build(),
+ SORT_KEY_NAME,
+ AttributeValue.builder().s("cd").build()));
+
+ WriteRequest putRequestTwo =
+ createPutItemRequest(
+ ImmutableMap.of(
+ PARTITION_KEY_NAME,
+ AttributeValue.builder().s("a").build(),
+ SORT_KEY_NAME,
+ AttributeValue.builder().s("bcd").build()));
+
+ PrimaryKeyBuilder keyBuilder =
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME, SORT_KEY_NAME));
+ Assertions.assertThat(keyBuilder.build(putRequestOne))
+ .isNotEqualTo(keyBuilder.build(putRequestTwo));
+ }
+
+ @Test
+ public void testPartitionKeysOfTwoDifferentRequestsEqual() {
+ PrimaryKeyBuilder keyBuilder = new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME));
+ Assertions.assertThat(keyBuilder.build(createPutItemRequest(createItemValues())))
+ .isEqualTo(keyBuilder.build(createDeleteItemRequest(createItemValues())));
+ }
+
+ @Test
+ public void testCompositeKeysOfTwoDifferentRequestsEqual() {
+ PrimaryKeyBuilder keyBuilder =
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME, SORT_KEY_NAME));
+
+ Assertions.assertThat(keyBuilder.build(createPutItemRequest(createItemValues())))
+ .isEqualTo(keyBuilder.build(createDeleteItemRequest(createItemValues())));
+ }
+
+ @Test(expected = InvalidRequestException.class)
+ public void testExceptOnEmptyRequest() {
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME))
+ .build(createPutItemRequest(new HashMap<>()));
+ }
+
+ @Test(expected = InvalidRequestException.class)
+ public void testExceptWhenNoPartitionKey() {
+ ImmutableMap<String, AttributeValue> itemValues =
+ ImmutableMap.of("some_item", AttributeValue.builder().bool(false).build());
+
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME))
+ .build(createPutItemRequest(itemValues));
+ }
+
+ @Test(expected = InvalidRequestException.class)
+ public void testExceptWhenEmptyKey() {
+ ImmutableMap<String, AttributeValue> itemValues =
+ ImmutableMap.of(PARTITION_KEY_NAME, AttributeValue.builder().s("").build());
+
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME))
+ .build(createPutItemRequest(itemValues));
+ }
+
+ @Test(expected = InvalidRequestException.class)
+ public void testExceptWhenNoPartitionKeyCompositeKey() {
+ ImmutableMap<String, AttributeValue> itemValues =
+ ImmutableMap.of(
+ SORT_KEY_NAME,
+ AttributeValue.builder().s("101112").build(),
+ "some_item",
+ AttributeValue.builder().bool(false).build());
+
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME))
+ .build(createPutItemRequest(itemValues));
+ }
+
+ @Test(expected = InvalidRequestException.class)
+ public void testExceptWhenNoSortKey() {
+ ImmutableMap<String, AttributeValue> itemValues =
+ ImmutableMap.of(
+ PARTITION_KEY_NAME,
+ AttributeValue.builder().s("101112").build(),
+ "some_item",
+ AttributeValue.builder().bool(false).build());
+
+ new PrimaryKeyBuilder(ImmutableList.of(PARTITION_KEY_NAME, SORT_KEY_NAME))
+ .build(createPutItemRequest(itemValues));
+ }
+}
diff --git a/flink-connector-dynamodb/src/test/resources/archunit.properties b/flink-connector-dynamodb/src/test/resources/archunit.properties
new file mode 100644
index 0000000..15be88c
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/resources/archunit.properties
@@ -0,0 +1,31 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License 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.
+#
+
+# By default we allow removing existing violations, but fail when new violations are added.
+freeze.store.default.allowStoreUpdate=true
+
+# Enable this if a new (frozen) rule has been added in order to create the initial store and record the existing violations.
+#freeze.store.default.allowStoreCreation=true
+
+# Enable this to add allow new violations to be recorded.
+# NOTE: Adding new violations should be avoided when possible. If the rule was correct to flag a new
+# violation, please try to avoid creating the violation. If the violation was created due to a
+# shortcoming of the rule, file a JIRA issue so the rule can be improved.
+#freeze.refreeze=true
+
+freeze.store.default.path=archunit-violations
diff --git a/flink-connector-dynamodb/src/test/resources/log4j2-test.properties b/flink-connector-dynamodb/src/test/resources/log4j2-test.properties
new file mode 100644
index 0000000..6faab06
--- /dev/null
+++ b/flink-connector-dynamodb/src/test/resources/log4j2-test.properties
@@ -0,0 +1,29 @@
+################################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License 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.
+################################################################################
+
+# Set root logger level to OFF to not flood build logs
+# set manually to INFO for debugging purposes
+rootLogger.level = OFF
+rootLogger.appenderRef.test.ref = TestLogger
+
+appender.testlogger.name = TestLogger
+appender.testlogger.type = CONSOLE
+appender.testlogger.target = SYSTEM_ERR
+appender.testlogger.layout.type = PatternLayout
+appender.testlogger.layout.pattern = %-4r [%t] %-5p %c %x - %m%n
+
diff --git a/pom.xml b/pom.xml
index 3c34faa..8fd32e7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -87,6 +87,7 @@ under the License.
<version>${project.parent.version}</version>
<scope>test</scope>
</dependency>
+
</dependencies>
</dependencyManagement>