Initial import from [1]

[1] https://review.gerrithub.io/admin/repos/GerritForge/plugins_aws-dynamodb

Change-Id: Ifb9380015d64d8b305ac4fcbae60fc057b2687fe
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..8c7a656
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,60 @@
+load("//tools/bzl:junit.bzl", "junit_tests")
+load(
+    "//tools/bzl:plugin.bzl",
+    "PLUGIN_DEPS",
+    "PLUGIN_TEST_DEPS",
+    "gerrit_plugin",
+)
+
+gerrit_plugin(
+    name = "aws-dynamodb-refdb",
+    srcs = glob(["src/main/java/**/*.java"]),
+    manifest_entries = [
+        "Gerrit-PluginName: aws-dynamodb-refdb",
+        "Gerrit-Module: com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Module",
+        "Implementation-Title: AWS DynamoDB shared ref-database implementation",
+        "Implementation-URL: https://gerrit-review.googlesource.com/#/admin/projects/plugins/aws-dynamodb-refdb",
+    ],
+    resources = glob(["src/main/resources/**/*"]),
+    deps = [
+        "@amazon-aws-core//jar",
+        "@amazon-dynamodb//jar",
+        "@amazon-regions//jar",
+        "@amazon-sdk-core//jar",
+        "@amazon-utils//jar",
+        "@aws-java-sdk-core//jar",
+        "@aws-java-sdk-dynamodb//jar",
+        "@dynamodb-lock-client//jar",
+        "@global-refdb//jar",
+        "@jackson-annotations//jar",
+        "@jackson-databind//jar",
+        "@jackson-dataformat-cbor//jar",
+        "@joda-time//jar",
+    ],
+)
+
+junit_tests(
+    name = "aws-dynamodb-refdb_tests",
+    srcs = glob(["src/test/java/**/*.java"]),
+    resources = glob(["src/test/resources/**/*"]),
+    tags = ["aws-dynamodb-refdb"],
+    deps = [
+        ":aws-dynamodb-refdb__plugin_test_deps",
+    ],
+)
+
+java_library(
+    name = "aws-dynamodb-refdb__plugin_test_deps",
+    testonly = 1,
+    visibility = ["//visibility:public"],
+    exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+        ":aws-dynamodb-refdb__plugin",
+        "@amazon-regions//jar",
+        "//lib/testcontainers",
+        "//lib/testcontainers:docker-java-api",
+        "//lib/testcontainers:docker-java-transport",
+        "@testcontainer-localstack//jar",
+        "@aws-java-sdk-dynamodb//jar",
+        "@global-refdb//jar",
+    ],
+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed 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.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..db69380
--- /dev/null
+++ b/README.md
@@ -0,0 +1,16 @@
+# Gerrit DynamoDB ref-db
+
+This plugin provides an implementation of the Gerrit global ref-db backed by
+[AWS DynamoDB](https://aws.amazon.com/dynamodb/).
+
+Requirements for using this plugin are:
+
+- Gerrit v3.2 or later
+- DynamoDB provisioned in AWS
+
+## Typical use-case
+
+The global ref-db is a typical use-case of a Gerrit multi-master scenario
+in a multi-site setup. Refer to the
+[Gerrit multi-site plugin](https://gerrit.googlesource.com/plugins/multi-site/+/master/DESIGN.md)
+for more details on the high level architecture.
diff --git a/external_plugin_deps.bzl b/external_plugin_deps.bzl
new file mode 100644
index 0000000..aed23bd
--- /dev/null
+++ b/external_plugin_deps.bzl
@@ -0,0 +1,84 @@
+load("//tools/bzl:maven_jar.bzl", "maven_jar")
+
+AWS_SDK_VER = "2.16.19"
+AWS_KINESIS_VER = "2.3.4"
+JACKSON_VER = "2.10.4"
+
+def external_plugin_deps():
+    maven_jar(
+        name = "amazon-dynamodb",
+        artifact = "software.amazon.awssdk:dynamodb:" + AWS_SDK_VER,
+        sha1 = "33ec7d291973658779b5777db2a0214a5c469e81",
+    )
+
+    maven_jar(
+        name = "aws-java-sdk-dynamodb",
+        artifact = "com.amazonaws:aws-java-sdk-dynamodb:1.11.1006",
+        sha1 = "dd2c9dff101ae8dad26197f7b09a06d4e13965ca",
+    )
+
+    maven_jar(
+        name = "dynamodb-lock-client",
+        artifact = "com.amazonaws:dynamodb-lock-client:1.1.0",
+        sha1 = "3aadced3599f3b2fd058bc75d48dde374f66e544",
+    )
+
+    maven_jar(
+        name = "amazon-regions",
+        artifact = "software.amazon.awssdk:regions:" + AWS_SDK_VER,
+        sha1 = "089f4f3d3ef20b2486f09e71da638c03100eab64",
+    )
+
+    maven_jar(
+        name = "amazon-sdk-core",
+        artifact = "software.amazon.awssdk:sdk-core:" + AWS_SDK_VER,
+        sha1 = "02a60fd9c138048272ef8b6c80ae67491dd386a9",
+    )
+
+    maven_jar(
+        name = "amazon-aws-core",
+        artifact = "software.amazon.awssdk:aws-core:" + AWS_SDK_VER,
+        sha1 = "0f50f5cf2698a0de7d2d77322cbf3fb13f76187f",
+    )
+
+    maven_jar(
+        name = "amazon-utils",
+        artifact = "software.amazon.awssdk:utils:" + AWS_SDK_VER,
+        sha1 = "53edaa1f884682ac3091293eff3eb024ed0e36bb",
+    )
+
+    maven_jar(
+        name = "aws-java-sdk-core",
+        artifact = "com.amazonaws:aws-java-sdk-core:1.11.960",
+        sha1 = "18b6b2a5cb83a0e2e33a593302b5dbe0ca2ade64",
+    )
+
+    maven_jar(
+        name = "jackson-databind",
+        artifact = "com.fasterxml.jackson.core:jackson-databind:" + JACKSON_VER,
+        sha1 = "76e9152e93d4cf052f93a64596f633ba5b1c8ed9",
+    )
+
+    maven_jar(
+        name = "jackson-dataformat-cbor",
+        artifact = "com.fasterxml.jackson.dataformat:jackson-dataformat-cbor:" + JACKSON_VER,
+        sha1 = "c854bb2d46138198cb5d4aae86ef6c04b8bc1e70",
+    )
+
+    maven_jar(
+        name = "joda-time",
+        artifact = "joda-time:joda-time:2.10.10",
+        sha1 = "29e8126e31f41e5c12b9fe3a7eb02e704c47d70b",
+    )
+
+    maven_jar(
+        name = "testcontainer-localstack",
+        artifact = "org.testcontainers:localstack:1.15.2",
+        sha1 = "ae3c4717bc5f37410abbb490cb46d349a77990a0",
+    )
+
+    maven_jar(
+        name = "global-refdb",
+        artifact = "com.gerritforge:global-refdb:3.3.2.1",
+        sha1 = "00b6b0f39b3c8fc280a19d91fb0681954ebccd02",
+    )
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/AmazonDynamoDBProvider.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/AmazonDynamoDBProvider.java
new file mode 100644
index 0000000..76ec8c0
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/AmazonDynamoDBProvider.java
@@ -0,0 +1,53 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
+import com.amazonaws.client.builder.AwsClientBuilder;
+import com.amazonaws.regions.DefaultAwsRegionProviderChain;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import software.amazon.awssdk.regions.Region;
+
+@Singleton
+class AmazonDynamoDBProvider implements Provider<AmazonDynamoDB> {
+  private final Configuration configuration;
+
+  @Inject
+  AmazonDynamoDBProvider(Configuration configuration) {
+    this.configuration = configuration;
+  }
+
+  @Override
+  public AmazonDynamoDB get() {
+    AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard();
+    String region =
+        configuration
+            .getRegion()
+            .map(Region::id)
+            .orElseGet(() -> new DefaultAwsRegionProviderChain().getRegion());
+
+    configuration
+        .getEndpoint()
+        .ifPresent(
+            endpoint ->
+                builder.withEndpointConfiguration(
+                    new AwsClientBuilder.EndpointConfiguration(endpoint.toASCIIString(), region)));
+    return builder.withCredentials(new DefaultAWSCredentialsProviderChain()).build();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Configuration.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Configuration.java
new file mode 100644
index 0000000..791e1c7
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Configuration.java
@@ -0,0 +1,76 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import com.google.common.base.Strings;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import java.net.URI;
+import java.util.Optional;
+import software.amazon.awssdk.regions.Region;
+
+@Singleton
+class Configuration {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+  protected static final String DEFAULT_REFS_DB_TABLE_NAME = "refsDb";
+  protected static final String DEFAULT_LOCKS_TABLE_NAME = "lockTable";
+  private final Optional<Region> region;
+  private final Optional<URI> endpoint;
+  private final String refsDbTableName;
+  private final String locksTableName;
+
+  @Inject
+  Configuration(PluginConfigFactory configFactory, @PluginName String pluginName) {
+    PluginConfig pluginConfig = configFactory.getFromGerritConfig(pluginName);
+
+    this.region = Optional.ofNullable(getStringParam(pluginConfig, "region")).map(Region::of);
+    this.endpoint = Optional.ofNullable(getStringParam(pluginConfig, "endpoint")).map(URI::create);
+    // TODO: add prefix
+    this.refsDbTableName = pluginConfig.getString("refsDbTableName", DEFAULT_REFS_DB_TABLE_NAME);
+    this.locksTableName = pluginConfig.getString("locksTableName", DEFAULT_LOCKS_TABLE_NAME);
+    logger.atInfo().log(
+        "dynamodb-refdb configuration: refsDbTableName: %s|locksTableName:%s%s%s",
+        refsDbTableName,
+        locksTableName,
+        region.map(r -> String.format("|region: %s", r.id())).orElse(""),
+        endpoint.map(e -> String.format("|endpoint: %s", e.toASCIIString())).orElse(""));
+  }
+
+  Optional<Region> getRegion() {
+    return region;
+  }
+
+  Optional<URI> getEndpoint() {
+    return endpoint;
+  }
+
+  private static String getStringParam(PluginConfig pluginConfig, String name) {
+    return Strings.isNullOrEmpty(System.getProperty(name))
+        ? pluginConfig.getString(name)
+        : System.getProperty(name);
+  }
+
+  String getRefsDbTableName() {
+    return refsDbTableName;
+  }
+
+  String getLocksTableName() {
+    return locksTableName;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLifeCycleManager.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLifeCycleManager.java
new file mode 100644
index 0000000..1003164
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLifeCycleManager.java
@@ -0,0 +1,130 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.LOCK_DB_PRIMARY_KEY;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.LOCK_DB_SORT_KEY;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.REF_DB_PRIMARY_KEY;
+
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
+import com.amazonaws.services.dynamodbv2.CreateDynamoDBTableOptions;
+import com.amazonaws.services.dynamodbv2.document.Table;
+import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
+import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
+import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
+import com.amazonaws.services.dynamodbv2.model.KeyType;
+import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
+import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException;
+import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
+import com.amazonaws.services.dynamodbv2.util.TableUtils;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+
+@Singleton
+class DynamoDBLifeCycleManager implements LifecycleListener {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+  private final Configuration configuration;
+  private final AmazonDynamoDB dynamoDB;
+
+  @Inject
+  DynamoDBLifeCycleManager(Configuration configuration, AmazonDynamoDB dynamoDB) {
+    this.configuration = configuration;
+    this.dynamoDB = dynamoDB;
+  }
+
+  // TODO: it is useful to create these at start up during development
+  // however ddb tables should be created beforehand, because it might take a while.
+  // Perhaps it'd be useful to move this logic to an SSH command.
+
+  @Override
+  public void start() {
+    createLockTableIfDoesntExist();
+    createRefsDbTableIfDoesntExist();
+  }
+
+  @Override
+  public void stop() {}
+
+  private void createLockTableIfDoesntExist() {
+    if (!tableExists(dynamoDB, configuration.getLocksTableName())) {
+      logger.atWarning().log(
+          "Attempt to create lock table '%s'", configuration.getLocksTableName());
+      AmazonDynamoDBLockClient.createLockTableInDynamoDB(
+          CreateDynamoDBTableOptions.builder(
+                  dynamoDB, new ProvisionedThroughput(10L, 10L), configuration.getLocksTableName())
+              .withPartitionKeyName(LOCK_DB_PRIMARY_KEY)
+              .withSortKeyName(LOCK_DB_SORT_KEY)
+              .build());
+
+      try {
+        logger.atWarning().log(
+            "Wait for lock table '%s' creation", configuration.getLocksTableName());
+        TableUtils.waitUntilActive(dynamoDB, configuration.getLocksTableName());
+        logger.atWarning().log(
+            "lock table '%s' successfully created and active", configuration.getLocksTableName());
+      } catch (InterruptedException e) {
+        logger.atSevere().withCause(e).log(
+            "Timeout when creating lock table '%s'", configuration.getLocksTableName());
+      }
+    } else {
+      logger.atWarning().log(
+          "Lock table '%s' already exists, nothing to do.", configuration.getLocksTableName());
+    }
+  }
+
+  private void createRefsDbTableIfDoesntExist() {
+    boolean created =
+        TableUtils.createTableIfNotExists(
+            dynamoDB,
+            new CreateTableRequest()
+                .withTableName(configuration.getRefsDbTableName())
+                .withAttributeDefinitions(
+                    new AttributeDefinition(REF_DB_PRIMARY_KEY, ScalarAttributeType.S))
+                .withKeySchema(new KeySchemaElement(REF_DB_PRIMARY_KEY, KeyType.HASH))
+                .withProvisionedThroughput(new ProvisionedThroughput(10L, 10L)));
+
+    if (created) {
+      try {
+        logger.atWarning().log(
+            "Wait for refsDB table '%s' creation", configuration.getRefsDbTableName());
+        TableUtils.waitUntilActive(dynamoDB, configuration.getRefsDbTableName());
+        logger.atWarning().log(
+            "refsDb table '%s' successfully created and active",
+            configuration.getRefsDbTableName());
+      } catch (InterruptedException e) {
+        logger.atSevere().withCause(e).log(
+            "Timeout when creating refsDb table '%s'", configuration.getRefsDbTableName());
+      }
+    } else {
+      logger.atWarning().log(
+          "RefsDb table '%s' already exists, nothing to do.", configuration.getRefsDbTableName());
+    }
+  }
+
+  @VisibleForTesting
+  static boolean tableExists(AmazonDynamoDB dynamoDB, String tableName) {
+    final Table table = new Table(dynamoDB, tableName);
+    try {
+      table.describe();
+    } catch (ResourceNotFoundException e) {
+      return false;
+    }
+    return true;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLockClientProvider.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLockClientProvider.java
new file mode 100644
index 0000000..42009f1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBLockClientProvider.java
@@ -0,0 +1,52 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.LOCK_DB_PRIMARY_KEY;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.LOCK_DB_SORT_KEY;
+
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClientOptions;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import java.util.concurrent.TimeUnit;
+
+@Singleton
+class DynamoDBLockClientProvider implements Provider<AmazonDynamoDBLockClient> {
+  private final Configuration configuration;
+  private final AmazonDynamoDB dynamoDB;
+
+  @Inject
+  DynamoDBLockClientProvider(Configuration configuration, AmazonDynamoDB dynamoDB) {
+    this.configuration = configuration;
+    this.dynamoDB = dynamoDB;
+  }
+
+  @Override
+  public AmazonDynamoDBLockClient get() {
+    final boolean createHeartbeatBackgroundThread = true;
+    return new AmazonDynamoDBLockClient(
+        AmazonDynamoDBLockClientOptions.builder(dynamoDB, configuration.getLocksTableName())
+            .withPartitionKeyName(LOCK_DB_PRIMARY_KEY)
+            .withSortKeyName(LOCK_DB_SORT_KEY)
+            .withTimeUnit(TimeUnit.SECONDS)
+            .withLeaseDuration(10L)
+            .withHeartbeatPeriod(3L)
+            .withCreateHeartbeatBackgroundThread(createHeartbeatBackgroundThread)
+            .build());
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabase.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabase.java
new file mode 100644
index 0000000..44822e9
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabase.java
@@ -0,0 +1,227 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import com.amazonaws.services.dynamodbv2.AcquireLockOptions;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
+import com.amazonaws.services.dynamodbv2.LockItem;
+import com.amazonaws.services.dynamodbv2.model.AttributeValue;
+import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
+import com.amazonaws.services.dynamodbv2.model.GetItemResult;
+import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException;
+import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
+import com.gerritforge.gerrit.globalrefdb.GlobalRefDatabase;
+import com.gerritforge.gerrit.globalrefdb.GlobalRefDbLockException;
+import com.gerritforge.gerrit.globalrefdb.GlobalRefDbSystemError;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.entities.Project;
+import com.google.inject.Inject;
+import java.util.Optional;
+import javax.inject.Singleton;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Ref;
+
+@Singleton
+public class DynamoDBRefDatabase implements GlobalRefDatabase {
+
+  public static final String REF_DB_PRIMARY_KEY = "refPath";
+  public static final String REF_DB_VALUE_KEY = "refValue";
+
+  public static final String LOCK_DB_PRIMARY_KEY = "lockKey";
+  public static final String LOCK_DB_SORT_KEY = "lockValue";
+
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+  private final AmazonDynamoDBLockClient lockClient;
+  private final AmazonDynamoDB dynamoDBClient;
+  private final Configuration configuration;
+
+  @Inject
+  DynamoDBRefDatabase(
+      AmazonDynamoDBLockClient lockClient,
+      AmazonDynamoDB dynamoDBClient,
+      Configuration configuration) {
+    this.lockClient = lockClient;
+    this.dynamoDBClient = dynamoDBClient;
+    this.configuration = configuration;
+  }
+
+  static String pathFor(Project.NameKey projectName, String refName) {
+    return "/" + projectName + "/" + refName;
+  }
+
+  @Override
+  public boolean isUpToDate(Project.NameKey project, Ref ref) throws GlobalRefDbLockException {
+    try {
+      GetItemResult result = getPathFromDynamoDB(project, ref.getName());
+      if (!exists(result)) {
+        return true;
+      }
+
+      String valueInDynamoDB = result.getItem().get(REF_DB_VALUE_KEY).getS();
+      ObjectId objectIdInSharedRefDb = ObjectId.fromString(valueInDynamoDB);
+      boolean isUpToDate = objectIdInSharedRefDb.equals(ref.getObjectId());
+
+      if (!isUpToDate) {
+        logger.atWarning().log(
+            "%s:%s is out of sync: local=%s dynamodb=%s",
+            project, ref.getName(), ref.getObjectId(), objectIdInSharedRefDb);
+      }
+      return isUpToDate;
+    } catch (Exception e) {
+      throw new GlobalRefDbLockException(project.get(), ref.getName(), e);
+    }
+  }
+
+  @Override
+  public boolean compareAndPut(Project.NameKey project, Ref currRef, ObjectId newRefValue)
+      throws GlobalRefDbSystemError {
+    ObjectId newValue = Optional.ofNullable(newRefValue).orElse(ObjectId.zeroId());
+    ObjectId currValue = Optional.ofNullable(currRef.getObjectId()).orElse(ObjectId.zeroId());
+
+    return doCompareAndPut(
+        project, pathFor(project, currRef.getName()), currValue.getName(), newValue.getName());
+  }
+
+  @Override
+  public <T> boolean compareAndPut(Project.NameKey project, String refName, T currValue, T newValue)
+      throws GlobalRefDbSystemError {
+    String refPath = pathFor(project, refName);
+
+    String newRefValue =
+        Optional.ofNullable(newValue).map(Object::toString).orElse(ObjectId.zeroId().getName());
+    String curRefValue =
+        Optional.ofNullable(currValue).map(Object::toString).orElse(ObjectId.zeroId().getName());
+
+    return doCompareAndPut(project, refPath, curRefValue, newRefValue);
+  }
+
+  private boolean doCompareAndPut(
+      Project.NameKey project, String refPath, String currValueForPath, String newValueForPath)
+      throws GlobalRefDbSystemError {
+    UpdateItemRequest updateItemRequest =
+        new UpdateItemRequest()
+            .withTableName(configuration.getRefsDbTableName())
+            .withKey(ImmutableMap.of(REF_DB_PRIMARY_KEY, new AttributeValue(refPath)))
+            .withExpressionAttributeValues(
+                ImmutableMap.of(
+                    ":old_value", new AttributeValue(currValueForPath),
+                    ":new_value", new AttributeValue(newValueForPath)))
+            .withUpdateExpression(String.format("SET %s = %s", REF_DB_VALUE_KEY, ":new_value"))
+            .withConditionExpression(
+                String.format(
+                    "attribute_not_exists(%s) OR %s = :old_value",
+                    REF_DB_PRIMARY_KEY, REF_DB_VALUE_KEY));
+    try {
+      dynamoDBClient.updateItem(updateItemRequest);
+      logger.atFine().log(
+          "Updated path for project %s. Current: %s New: %s",
+          project.get(), currValueForPath, newValueForPath);
+      return true;
+    } catch (ConditionalCheckFailedException e) {
+      throw new GlobalRefDbSystemError(
+          String.format(
+              "Conditional Check Failure when updating refPath %s. expected: %s New: %s",
+              refPath, currValueForPath, newValueForPath),
+          e);
+    } catch (Exception e) {
+      throw new GlobalRefDbSystemError(
+          String.format(
+              "Error updating refPath %s. expected: %s new: %s",
+              project.get(), currValueForPath, newValueForPath),
+          e);
+    }
+  }
+
+  @Override
+  public AutoCloseable lockRef(Project.NameKey project, String refName)
+      throws GlobalRefDbLockException {
+    String refPath = pathFor(project, refName);
+    try {
+      // Attempts to acquire a lock until it either acquires the lock, or a specified
+      // additionalTimeToWaitForLock is reached.
+      // TODO: 'additionalTimeToWaitForLock' should be configurable
+      // Hydrate with instanceId and ServerId and CurrentUser and Thread
+      LockItem lockItem =
+          lockClient.acquireLock(AcquireLockOptions.builder(refPath).withSortKey(refPath).build());
+      logger.atFine().log("Acquired lock for %s", refPath);
+      return lockItem;
+    } catch (InterruptedException e) {
+      logger.atSevere().withCause(e).log(
+          "Received interrupted signal when trying to acquire lock for %s", refPath);
+      throw new GlobalRefDbLockException(project.get(), refName, e);
+    } catch (LockNotGrantedException e) {
+      logger.atSevere().withCause(e).log("Failed to acquire lock for %s", refPath);
+      throw new GlobalRefDbLockException(project.get(), refName, e);
+    }
+  }
+
+  @Override
+  public boolean exists(Project.NameKey project, String refName) {
+    try {
+      if (!exists(getPathFromDynamoDB(project, refName))) {
+        logger.atFine().log("ref '%s' does not exist in dynamodb", pathFor(project, refName));
+        return false;
+      }
+      return true;
+
+    } catch (Exception e) {
+      logger.atSevere().withCause(e).log(
+          "Could not check for '%s' existence", pathFor(project, refName));
+    }
+
+    return false;
+  }
+
+  @Override
+  public void remove(Project.NameKey project) throws GlobalRefDbSystemError {
+    // TODO: to remove all refs related to project we'd need to be able to query
+    // dynamodb by 'project': perhaps we should have a composite key of:
+    // PK: project, SK: ref
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public <T> Optional<T> get(Project.NameKey project, String refName, Class<T> clazz)
+      throws GlobalRefDbSystemError {
+    try {
+      GetItemResult item = getPathFromDynamoDB(project, refName);
+      if (!exists(item)) {
+        return Optional.empty();
+      }
+      String refValue = item.getItem().get(REF_DB_VALUE_KEY).getS();
+
+      // TODO: not every string might be cast to T (it should work now because the
+      // only usage of this function requests string, but we should be serializing
+      // deserializing objects before adding them to dynamo.
+      return Optional.ofNullable((T) refValue);
+    } catch (Exception e) {
+      logger.atSevere().withCause(e).log("Cannot get value for %s", pathFor(project, refName));
+      return Optional.empty();
+    }
+  }
+
+  private GetItemResult getPathFromDynamoDB(Project.NameKey project, String refName) {
+    return dynamoDBClient.getItem(
+        configuration.getRefsDbTableName(),
+        ImmutableMap.of(REF_DB_PRIMARY_KEY, new AttributeValue(pathFor(project, refName))),
+        true);
+  }
+
+  private boolean exists(GetItemResult result) {
+    return result.getItem() != null && !result.getItem().isEmpty();
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Module.java b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Module.java
new file mode 100644
index 0000000..946d401
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/Module.java
@@ -0,0 +1,40 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import static com.google.inject.Scopes.SINGLETON;
+
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDBLockClient;
+import com.gerritforge.gerrit.globalrefdb.GlobalRefDatabase;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.extensions.registration.DynamicItem;
+import com.google.gerrit.lifecycle.LifecycleModule;
+import com.google.inject.Scopes;
+
+class Module extends LifecycleModule {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+  @Override
+  protected void configure() {
+    logger.atInfo().log("Shared ref-db engine: DynamoDB");
+    DynamicItem.bind(binder(), GlobalRefDatabase.class)
+        .to(DynamoDBRefDatabase.class)
+        .in(Scopes.SINGLETON);
+    bind(AmazonDynamoDB.class).toProvider(AmazonDynamoDBProvider.class).in(SINGLETON);
+    bind(AmazonDynamoDBLockClient.class).toProvider(DynamoDBLockClientProvider.class).in(SINGLETON);
+    listener().to(DynamoDBLifeCycleManager.class);
+  }
+}
diff --git a/src/main/resources/Documentation/Build.md b/src/main/resources/Documentation/Build.md
new file mode 100644
index 0000000..9d1670f
--- /dev/null
+++ b/src/main/resources/Documentation/Build.md
@@ -0,0 +1,22 @@
+# Build
+
+The aws-dynamodb-refdb plugin can be build as a regular 'in-tree' plugin. That means
+that is required to clone a Gerrit source tree first and then to have the plugin
+source directory into the `/plugins` path.
+
+Additionally, the `plugins/external_plugin_deps.bzl` file needs to be updated to
+match the aws-dynamodb-refdb plugin one.
+
+```shell script
+git clone --recursive https://gerrit.googlesource.com/gerrit
+cd gerrit
+git clone "https://gerrit.googlesource.com/plugins/aws-dynamodb-refdb" plugins/aws-dynamodb-refdb
+ln -sf plugins/aws-dynamodb-refdb/external_plugin_deps.bzl plugins/.
+bazelisk build plugins/aws-dynamodb-refdb
+```
+
+The output is created in
+
+```
+bazel-genfiles/plugins/aws-dynamodb-refdb/aws-dynamodb-refdb.jar
+```
\ No newline at end of file
diff --git a/src/main/resources/Documentation/config.md b/src/main/resources/Documentation/config.md
new file mode 100644
index 0000000..ca94b64
--- /dev/null
+++ b/src/main/resources/Documentation/config.md
@@ -0,0 +1,36 @@
+Configuration
+=========================
+
+The dynamodb-refdb plugin is configured by adding a plugin stanza in the
+`gerrit.config` file, for example:
+
+```text
+[plugin "aws-dynamodb-refdb"]
+    region = us-east-1
+    endpoint = http://localhost:4566
+    locksTableName = lockTable
+    refsDbTableName = refsDb
+```
+
+`plugin.aws-dynamodb-refdb.region`
+:   Optional. Which AWS region to connect to.
+Default: When not specified this value is provided via the default Region
+Provider Chain, as explained [here](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html)
+
+`plugin.aws-dynamodb-refdb.endpoint`
+:   Optional. When defined, it will override the default dynamodb endpoint
+will connect to it, rather than connecting to AWS. This is useful when
+developing or testing, in order to connect locally.
+See [localstack](https://github.com/localstack/localstack) to understand
+more about how run dynamodb stack outside AWS.
+Default: <empty>
+
+`plugin.aws-dynamodb-refdb.locksTableName`
+:   Optional. The name of the dynamoDB table used to store distribute locking
+See [DynamoDB lock client](https://github.com/awslabs/amazon-dynamodb-lock-client)
+
+`plugin.aws-dynamodb-refdb.locksTableName`
+:   Optional. The name of the dynamoDB table used to store git refs and their
+associated sha1.
+
+
diff --git a/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/ConfigurationTest.java b/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/ConfigurationTest.java
new file mode 100644
index 0000000..5195c01
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/ConfigurationTest.java
@@ -0,0 +1,121 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Configuration.DEFAULT_LOCKS_TABLE_NAME;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Configuration.DEFAULT_REFS_DB_TABLE_NAME;
+import static org.mockito.Mockito.when;
+
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import java.net.URI;
+import org.eclipse.jgit.lib.Config;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import software.amazon.awssdk.regions.Region;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ConfigurationTest {
+  private static final String PLUGIN_NAME = "aws-dynamodb-refdb";
+
+  @Mock private PluginConfigFactory pluginConfigFactoryMock;
+  private PluginConfig.Update pluginConfig;
+
+  @Before
+  public void setup() {
+    pluginConfig = PluginConfig.Update.forTest(PLUGIN_NAME, new Config());
+  }
+
+  @Test
+  public void shouldReadDefaultLocksTableName() {
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getLocksTableName()).isEqualTo(DEFAULT_LOCKS_TABLE_NAME);
+  }
+
+  @Test
+  public void shouldReadDefaultRefsDbTableName() {
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getRefsDbTableName()).isEqualTo(DEFAULT_REFS_DB_TABLE_NAME);
+  }
+
+  @Test
+  public void shouldReadConfiguredLocksTableName() {
+    pluginConfig.setString("locksTableName", "foobar");
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getLocksTableName()).isEqualTo("foobar");
+  }
+
+  @Test
+  public void shouldReadConfiguredRefsDbTableName() {
+    pluginConfig.setString("refsDbTableName", "foobar");
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getRefsDbTableName()).isEqualTo("foobar");
+  }
+
+  @Test
+  public void shouldReadEmptyEndpointByDefault() {
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getEndpoint().isPresent()).isFalse();
+  }
+
+  @Test
+  public void shouldReadConfiguredEndpoint() {
+    URI endpoint = URI.create("http:://localhost:4566");
+    pluginConfig.setString("endpoint", endpoint.toASCIIString());
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getEndpoint().get()).isEqualTo(endpoint);
+  }
+
+  @Test
+  public void shouldReadEmptyRegionByDefault() {
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getRegion().isPresent()).isFalse();
+  }
+
+  @Test
+  public void shouldReadConfiguredRegion() {
+    pluginConfig.setString("region", "eu-central-1");
+    when(pluginConfigFactoryMock.getFromGerritConfig(PLUGIN_NAME))
+        .thenReturn(pluginConfig.asPluginConfig());
+
+    Configuration configuration = new Configuration(pluginConfigFactoryMock, PLUGIN_NAME);
+    assertThat(configuration.getRegion().get()).isEqualTo(Region.EU_CENTRAL_1);
+  }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabaseIT.java b/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabaseIT.java
new file mode 100644
index 0000000..ba9b81d
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/validation/dfsrefdb/dynamodb/DynamoDBRefDatabaseIT.java
@@ -0,0 +1,256 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed 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 com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
+import static com.google.gerrit.testing.GerritJUnit.assertThrows;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Configuration.DEFAULT_LOCKS_TABLE_NAME;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Configuration.DEFAULT_REFS_DB_TABLE_NAME;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.REF_DB_PRIMARY_KEY;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.REF_DB_VALUE_KEY;
+import static com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.DynamoDBRefDatabase.pathFor;
+import static org.testcontainers.containers.localstack.LocalStackContainer.Service.DYNAMODB;
+
+import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
+import com.amazonaws.services.dynamodbv2.model.AttributeValue;
+import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
+import com.gerritforge.gerrit.globalrefdb.GlobalRefDbSystemError;
+import com.google.common.collect.ImmutableMap;
+import com.google.gerrit.acceptance.LightweightPluginDaemonTest;
+import com.google.gerrit.acceptance.TestPlugin;
+import com.google.gerrit.acceptance.WaitUtil;
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.entities.Project;
+import java.time.Duration;
+import java.util.Optional;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectIdRef;
+import org.eclipse.jgit.lib.Ref;
+import org.junit.Before;
+import org.junit.Test;
+import org.testcontainers.containers.localstack.LocalStackContainer;
+import org.testcontainers.utility.DockerImageName;
+
+@TestPlugin(
+    name = "aws-dynamodb-refdb",
+    sysModule = "com.googlesource.gerrit.plugins.validation.dfsrefdb.dynamodb.Module")
+public class DynamoDBRefDatabaseIT extends LightweightPluginDaemonTest {
+  private static final Duration DYNAMODB_TABLE_CREATION_TIMEOUT = Duration.ofSeconds(10);
+
+  private static final int LOCALSTACK_PORT = 4566;
+  private static final LocalStackContainer localstack =
+      new LocalStackContainer(DockerImageName.parse("localstack/localstack:0.12.8"))
+          .withServices(DYNAMODB)
+          .withExposedPorts(LOCALSTACK_PORT);
+
+  @Before
+  public void setUpTestPlugin() throws Exception {
+    localstack.start();
+
+    System.setProperty("endpoint", localstack.getEndpointOverride(DYNAMODB).toASCIIString());
+    System.setProperty("region", localstack.getRegion());
+    System.setProperty("aws.accessKeyId", localstack.getAccessKey());
+
+    // The secret key property name has changed from aws-sdk 1.11.x and 2.x [1]
+    // Export both names so that default credential provider chains work regardless
+    // he underlying library version.
+    // https: // docs.aws.amazon.com/sdk-for-java/latest/migration-guide/client-credential.html
+    System.setProperty("aws.secretKey", localstack.getSecretKey());
+    System.setProperty("aws.secretAccessKey", localstack.getSecretKey());
+
+    super.setUpTestPlugin();
+  }
+
+  @Override
+  public void tearDownTestPlugin() {
+    localstack.close();
+
+    super.tearDownTestPlugin();
+  }
+
+  @Test
+  public void shouldEnsureLockTableExists() throws Exception {
+    WaitUtil.waitUntil(
+        () -> DynamoDBLifeCycleManager.tableExists(dynamoDBClient(), DEFAULT_LOCKS_TABLE_NAME),
+        DYNAMODB_TABLE_CREATION_TIMEOUT);
+  }
+
+  @Test
+  public void shouldEnsureRefsDbTableExists() throws Exception {
+    WaitUtil.waitUntil(
+        () -> DynamoDBLifeCycleManager.tableExists(dynamoDBClient(), DEFAULT_REFS_DB_TABLE_NAME),
+        DYNAMODB_TABLE_CREATION_TIMEOUT);
+  }
+
+  @Test
+  public void getShouldBeEmptyWhenRefDoesntExists() throws Exception {
+    Optional<String> maybeRef = dynamoDBRefDatabase().get(project, "refs/not/in/db", String.class);
+
+    assertThat(maybeRef).isEmpty();
+  }
+
+  @Test
+  public void getShouldReturnRefValueWhenItExists() throws Exception {
+    String refName = "refs/changes/01/01/meta";
+    String refValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+    createRefInDynamoDB(project, refName, refValue);
+
+    Optional<String> maybeRef = dynamoDBRefDatabase().get(project, refName, String.class);
+
+    assertThat(maybeRef).hasValue(refValue);
+  }
+
+  @Test
+  public void existsShouldReturnFalseWhenRefIsNotStored() throws Exception {
+    assertThat(dynamoDBRefDatabase().exists(project, "refs/not/in/db")).isFalse();
+  }
+
+  @Test
+  public void existShouldReturnTrueWhenRefIsStored() throws Exception {
+    String refName = "refs/changes/01/01/meta";
+    String refValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+    createRefInDynamoDB(project, refName, refValue);
+
+    assertThat(dynamoDBRefDatabase().exists(project, refName)).isTrue();
+  }
+
+  @Test
+  public void isUpToDateShouldReturnTrueWhenRefPointsToTheStoredRefValue() throws Exception {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+
+    createRefInDynamoDB(project, refName, currentRefValue);
+
+    assertThat(dynamoDBRefDatabase().isUpToDate(project, refOf(refName, currentRefValue))).isTrue();
+  }
+
+  @Test
+  public void isUpToDateShouldReturnFalseWhenRefDoesNotPointToTheStoredRefValue() {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+    String previousRefValue = "9f6f2963cf44505428c61b935ff1ca65372cf28c";
+
+    createRefInDynamoDB(project, refName, previousRefValue);
+
+    assertThat(dynamoDBRefDatabase().isUpToDate(project, refOf(refName, currentRefValue)))
+        .isFalse();
+  }
+
+  @Test
+  public void isUpToDateShouldBeConsideredTrueWhenNoPreviousRefExists() {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+
+    assertThat(dynamoDBRefDatabase().isUpToDate(project, refOf(refName, currentRefValue))).isTrue();
+  }
+
+  @Test
+  public void compareAndPutShouldBeSuccessfulWhenNoPreviousRefExists() {
+    String refName = "refs/changes/01/01/meta";
+    String newRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+
+    assertThat(
+            dynamoDBRefDatabase()
+                .compareAndPut(project, refOf(refName, null), ObjectId.fromString(newRefValue)))
+        .isTrue();
+  }
+
+  @Test
+  public void compareAndPutShouldSuccessfullyUpdateRemovedRef() throws Exception {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+
+    createRefInDynamoDB(project, refName, currentRefValue);
+
+    assertThat(
+            dynamoDBRefDatabase()
+                .compareAndPut(project, refOf(refName, currentRefValue), ObjectId.zeroId()))
+        .isTrue();
+  }
+
+  @Test
+  public void compareAndPutShouldThrowWhenStoredRefIsNotExpected() {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+    String newRefValue = "9f6f2963cf44505428c61b935ff1ca65372cf28c";
+    String expectedRefValue = "875ce4b14278b64be61478f91a40cf480758bfba";
+    Ref expectedRef = refOf(refName, expectedRefValue);
+
+    createRefInDynamoDB(project, refName, currentRefValue);
+
+    GlobalRefDbSystemError thrown =
+        assertThrows(
+            GlobalRefDbSystemError.class,
+            () ->
+                dynamoDBRefDatabase()
+                    .compareAndPut(project, expectedRef, ObjectId.fromString(newRefValue)));
+    assertThat(thrown)
+        .hasMessageThat()
+        .containsMatch(
+            "Conditional Check Failure when updating refPath.*expected:.*"
+                + expectedRefValue
+                + " New:.*"
+                + newRefValue);
+  }
+
+  @Test
+  public void compareAndPutStringsShouldBeSuccessful() throws Exception {
+    String refName = "refs/changes/01/01/meta";
+    String currentRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+    String newRefValue = "9f6f2963cf44505428c61b935ff1ca65372cf28c";
+
+    createRefInDynamoDB(project, refName, currentRefValue);
+
+    assertThat(dynamoDBRefDatabase().compareAndPut(project, refName, currentRefValue, newRefValue))
+        .isTrue();
+  }
+
+  @Test
+  public void compareAndPutStringsShouldBeSuccessfulWhenNoPreviousRefExists() {
+    String refName = "refs/changes/01/01/meta";
+    String newRefValue = "533d3ccf8a650fb26380faa732921a2c74924d5c";
+
+    assertThat(dynamoDBRefDatabase().compareAndPut(project, refName, null, newRefValue)).isTrue();
+  }
+
+  private AmazonDynamoDB dynamoDBClient() {
+    return plugin.getSysInjector().getInstance(AmazonDynamoDB.class);
+  }
+
+  private DynamoDBRefDatabase dynamoDBRefDatabase() {
+    return plugin.getSysInjector().getInstance(DynamoDBRefDatabase.class);
+  }
+
+  private void createRefInDynamoDB(Project.NameKey project, String refPath, String refValue) {
+    dynamoDBClient()
+        .putItem(
+            new PutItemRequest()
+                .withTableName(DEFAULT_REFS_DB_TABLE_NAME)
+                .withItem(
+                    ImmutableMap.of(
+                        REF_DB_PRIMARY_KEY,
+                        new AttributeValue(pathFor(project, refPath)),
+                        REF_DB_VALUE_KEY,
+                        new AttributeValue(refValue))));
+  }
+
+  private Ref refOf(String refName, @Nullable String objectIdSha1) {
+    return new ObjectIdRef.Unpeeled(
+        Ref.Storage.NETWORK,
+        refName,
+        Optional.ofNullable(objectIdSha1).map(ObjectId::fromString).orElse(null));
+  }
+}