Merge branch 'stable-2.16'

* stable-2.16:
  Add README, LICENSE, and DESIGN
  Remove all identical duplicate methods in IndexEventForwarder
  SourceAwareEventWrapper: rename header to EventHeader
  Fix typo in the retry warning
  Retry upon consuming project-index messages
  ForwardedIndexGroupHandler: do not use UUID as key
  EventConsumerIT: createChange should create patchset-created
  Increase Kafka receive patience to 30s
  ForwardedIndexProjectHandler: don't use Project.NameKey

Change-Id: If1e99b52fb1e98a703082324cfaf21167c1dcb66
diff --git a/src/main/resources/Documentation/design.md b/DESIGN.md
similarity index 98%
rename from src/main/resources/Documentation/design.md
rename to DESIGN.md
index e3b7ecc..7d595ee 100644
--- a/src/main/resources/Documentation/design.md
+++ b/DESIGN.md
@@ -260,7 +260,7 @@
 The combination of the above components makes the Gerrit multi-site
 configuration possible.
 
-![Initial Multi-Site Plugin Architecture](./architecture-first-iteration.png)
+![Initial Multi-Site Plugin Architecture](./images/architecture-first-iteration.png)
 
 ## Current implementation Details
 
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /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..89f9e78
--- /dev/null
+++ b/README.md
@@ -0,0 +1,91 @@
+# Gerrit multi-site plugin
+
+This plugin allows having multiple Gerrit masters to be deployed across various
+sites without having to share any storage. The alignment between the masters
+happens using the replication plugin and an external message broker.
+
+The Gerrit masters requirements are:
+
+- Gerrit v2.16.5 or later
+- Migrated to NoteDb
+- Connected to the same message broker
+- Accessible behind a load balancer (e.g., HAProxy)
+
+Currently, the only mode supported is one primary read/write master
+and multiple read-only masters but eventually the plan is to support N
+read/write masters. The read/write master is handling any traffic while the
+read-only masters are serving the Gerrit GUI assets, the HTTP GET REST API and
+the git-upload-packs. The read-only masters are kept updated to be always ready
+to become a read/write master.
+
+For more details on the overall multi-site design and roadmap, please refer
+to the [multi-site plugin DESIGN.md document](DESIGN.md)
+
+## License
+
+This plugin is released under the same Apache 2.0 license and copyright holders
+as of the Gerrit Code Review project.
+
+## How to build
+
+The multi-site plugin is built like any other Gerrit plugin in tree mode, by cloning
+Gerrit and the multi-site plugin code, and checking them out on the desired branch.
+
+Example of cloning Gerrit and multi-site for a stable-2.16 build:
+
+```
+git clone -b stable-2.16 https://gerrit.googlesource.com/gerrit
+git clone -b stable-2.16 https://gerrit.googlesource.com/plugins/multi-site
+
+cd gerrit/plugins
+ln -s ../../multi-site .
+rm external_plugin_deps.bzl
+ln -s multi-site/external_plugin_deps.bzl .
+```
+
+Example of building the multi-site plugin:
+
+```
+cd gerrit
+bazel build plugins/multi-site
+```
+
+The multi-site.jar plugin is generated to `bazel-genfiles/plugins/multi-site/multi-site.jar`.
+
+Example of testing the multi-site plugin:
+
+```
+cd gerrit
+bazel test plugins/multi-site:multi_site_tests
+```
+
+**NOTE**: The multi-site tests include also the use of Docker containers for
+instantiating and using a Kafka/Zookeeper broker. Make sure you have a Docker
+daemon running (/var/run/docker.sock accessible) or a DOCKER_HOST pointing to
+a Docker server.
+
+## How to configure
+
+Install the multi-site plugin into the `$GERRIT_SITE/plugins` directory of all
+the Gerrit servers that are part of the multi-site cluster.
+
+Create the `$GERRIT_SITE/etc/multi-site.config` on all Gerrit servers with the
+following basic settings:
+
+```
+[kafka]
+  bootstrapServers = <kafka-host>:<kafka-port>
+
+[kafka "publisher"]
+  enabled = true
+
+[kafka "subscriber"]
+  enabled = true
+```
+
+For more details on the configuration settings, please refer to the
+[multi-site configuration documentation](src/main/resources/Documentation/config.md).
+
+You need also to setup the Git-level replication between nodes, for more details
+please refer to the
+[replication plugin documentation](https://gerrit.googlesource.com/plugins/replication/+/refs/heads/master/src/main/resources/Documentation/config.md).
diff --git a/src/main/resources/Documentation/architecture-first-iteration.png b/images/architecture-first-iteration.png
similarity index 100%
rename from src/main/resources/Documentation/architecture-first-iteration.png
rename to images/architecture-first-iteration.png
Binary files differ
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/broker/BrokerPublisher.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/broker/BrokerPublisher.java
index db13229..11310b5 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/broker/BrokerPublisher.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/broker/BrokerPublisher.java
@@ -68,7 +68,7 @@
   private SourceAwareEventWrapper toBrokerEvent(Event event) {
     JsonObject body = eventToJson(event);
     return new SourceAwareEventWrapper(
-        new SourceAwareEventWrapper.KafkaEventHeader(
+        new SourceAwareEventWrapper.EventHeader(
             UUID.randomUUID(), event.getType(), instanceId, event.eventCreatedOn),
         body);
   }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandler.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandler.java
index c89a9d5..700397d 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandler.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandler.java
@@ -32,7 +32,7 @@
  */
 @Singleton
 public class ForwardedIndexGroupHandler
-    extends ForwardedIndexingHandler<AccountGroup.UUID, GroupIndexEvent> {
+    extends ForwardedIndexingHandler<String, GroupIndexEvent> {
   private final GroupIndexer indexer;
 
   @Inject
@@ -42,14 +42,14 @@
   }
 
   @Override
-  protected void doIndex(AccountGroup.UUID uuid, Optional<GroupIndexEvent> event)
+  protected void doIndex(String uuid, Optional<GroupIndexEvent> event)
       throws IOException, OrmException {
-    indexer.index(uuid);
+    indexer.index(new AccountGroup.UUID(uuid));
     log.debug("Group {} successfully indexed", uuid);
   }
 
   @Override
-  protected void doDelete(AccountGroup.UUID uuid, Optional<GroupIndexEvent> event) {
+  protected void doDelete(String uuid, Optional<GroupIndexEvent> event) {
     throw new UnsupportedOperationException("Delete from group index not supported");
   }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandler.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandler.java
index 3e4e22e..ff2e111 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandler.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandler.java
@@ -20,8 +20,12 @@
 import com.google.inject.Singleton;
 import com.googlesource.gerrit.plugins.multisite.Configuration;
 import com.googlesource.gerrit.plugins.multisite.forwarder.events.ProjectIndexEvent;
+import com.googlesource.gerrit.plugins.multisite.index.ForwardedIndexExecutor;
+import com.googlesource.gerrit.plugins.multisite.index.ProjectChecker;
 import java.io.IOException;
 import java.util.Optional;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Index a project using {@link ProjectIndexer}. This class is meant to be used on the receiving
@@ -31,24 +35,87 @@
  */
 @Singleton
 public class ForwardedIndexProjectHandler
-    extends ForwardedIndexingHandler<Project.NameKey, ProjectIndexEvent> {
+    extends ForwardedIndexingHandler<String, ProjectIndexEvent> {
   private final ProjectIndexer indexer;
+  private final int retryInterval;
+  private final int maxTries;
+  private final ProjectChecker projectChecker;
+  private final ScheduledExecutorService indexExecutor;
 
   @Inject
-  ForwardedIndexProjectHandler(ProjectIndexer indexer, Configuration config) {
+  ForwardedIndexProjectHandler(
+      ProjectIndexer indexer,
+      ProjectChecker projectChecker,
+      @ForwardedIndexExecutor ScheduledExecutorService indexExecutor,
+      Configuration config) {
     super(config.index().numStripedLocks());
     this.indexer = indexer;
+    Configuration.Index indexConfig = config.index();
+    this.retryInterval = indexConfig != null ? indexConfig.retryInterval() : 0;
+    this.maxTries = indexConfig != null ? indexConfig.maxTries() : 0;
+    this.indexExecutor = indexExecutor;
+    this.projectChecker = projectChecker;
   }
 
   @Override
-  protected void doIndex(Project.NameKey projectName, Optional<ProjectIndexEvent> event)
+  protected void doIndex(String projectName, Optional<ProjectIndexEvent> event) throws IOException {
+    if (!attemptIndex(projectName, event)) {
+      log.warn("First Attempt failed, scheduling again after {} msecs", retryInterval);
+      rescheduleIndex(projectName, event, 1);
+    }
+  }
+
+  public boolean attemptIndex(String projectName, Optional<ProjectIndexEvent> event)
       throws IOException {
-    indexer.index(projectName);
-    log.debug("Project {} successfully indexed", projectName);
+    log.debug("Attempt to index project {}, event: [{}]", projectName, event);
+    final Project.NameKey projectNameKey = new Project.NameKey(projectName);
+    if (projectChecker.isProjectUpToDate(projectNameKey)) {
+      indexer.index(projectNameKey);
+      log.debug("Project {} successfully indexed", projectName);
+      return true;
+    }
+    return false;
+  }
+
+  public void rescheduleIndex(
+      String projectName, Optional<ProjectIndexEvent> event, int retryCount) {
+    if (retryCount > maxTries) {
+      log.error(
+          "Project {} could not be indexed after {} retries. index could be stale.",
+          projectName,
+          retryCount);
+
+      return;
+    }
+
+    log.warn(
+        "Retrying for the #{} time to index project {} after {} msecs",
+        retryCount,
+        projectName,
+        retryInterval);
+
+    indexExecutor.schedule(
+        () -> {
+          Context.setForwardedEvent(true);
+          try {
+            if (!attemptIndex(projectName, event)) {
+              log.warn(
+                  "Attempt {} to index project {} failed, scheduling again after {} msecs",
+                  retryCount,
+                  projectName,
+                  retryInterval);
+              rescheduleIndex(projectName, event, retryCount + 1);
+            }
+          } catch (IOException e) {
+            log.warn("Project {} could not be indexed", projectName, e);
+          }
+        },
+        retryInterval,
+        TimeUnit.MILLISECONDS);
   }
 
   @Override
-  protected void doDelete(Project.NameKey projectName, Optional<ProjectIndexEvent> event) {
+  protected void doDelete(String projectName, Optional<ProjectIndexEvent> event) {
     throw new UnsupportedOperationException("Delete from project index not supported");
   }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/IndexEventForwarder.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/IndexEventForwarder.java
index 5efc0ba..701c2fe 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/IndexEventForwarder.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/IndexEventForwarder.java
@@ -14,49 +14,15 @@
 
 package com.googlesource.gerrit.plugins.multisite.forwarder;
 
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.AccountIndexEvent;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.ChangeIndexEvent;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.GroupIndexEvent;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.ProjectIndexEvent;
+import com.googlesource.gerrit.plugins.multisite.forwarder.events.IndexEvent;
 
 public interface IndexEventForwarder {
-  /**
-   * Forward a account indexing event to the other master.
-   *
-   * @param accountIndexEvent the details of the account index event.
-   * @return true if successful, otherwise false.
-   */
-  boolean indexAccount(AccountIndexEvent accountIndexEvent);
 
   /**
-   * Forward a change indexing event to the other master.
+   * Publish an indexing event to the broker.
    *
-   * @param changeIndexEvent the details of the change index event.
+   * @param event the details of the index event.
    * @return true if successful, otherwise false.
    */
-  boolean indexChange(ChangeIndexEvent changeIndexEvent);
-
-  /**
-   * Forward a delete change from index event to the other master.
-   *
-   * @param changeIndexEvent the details of the change index event.
-   * @return rue if successful, otherwise false.
-   */
-  boolean deleteChangeFromIndex(ChangeIndexEvent changeIndexEvent);
-
-  /**
-   * Forward a group indexing event to the other master.
-   *
-   * @param groupIndexEvent the details of the index event.
-   * @return true if successful, otherwise false.
-   */
-  boolean indexGroup(GroupIndexEvent groupIndexEvent);
-
-  /**
-   * Forward a project indexing event to the other master.
-   *
-   * @param projectIndexEvent the details of the index event.
-   * @return true if successful, otherwise false.
-   */
-  boolean indexProject(ProjectIndexEvent projectIndexEvent);
+  boolean index(IndexEvent event);
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/broker/BrokerIndexEventForwarder.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/broker/BrokerIndexEventForwarder.java
index ed7d113..bf70c84 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/broker/BrokerIndexEventForwarder.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/forwarder/broker/BrokerIndexEventForwarder.java
@@ -17,11 +17,8 @@
 import com.google.inject.Inject;
 import com.googlesource.gerrit.plugins.multisite.broker.BrokerPublisher;
 import com.googlesource.gerrit.plugins.multisite.forwarder.IndexEventForwarder;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.AccountIndexEvent;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.ChangeIndexEvent;
 import com.googlesource.gerrit.plugins.multisite.forwarder.events.EventFamily;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.GroupIndexEvent;
-import com.googlesource.gerrit.plugins.multisite.forwarder.events.ProjectIndexEvent;
+import com.googlesource.gerrit.plugins.multisite.forwarder.events.IndexEvent;
 
 public class BrokerIndexEventForwarder implements IndexEventForwarder {
   private final BrokerPublisher publisher;
@@ -32,27 +29,7 @@
   }
 
   @Override
-  public boolean indexAccount(AccountIndexEvent event) {
-    return publisher.publishEvent(EventFamily.INDEX_EVENT, event);
-  }
-
-  @Override
-  public boolean indexChange(ChangeIndexEvent event) {
-    return publisher.publishEvent(EventFamily.INDEX_EVENT, event);
-  }
-
-  @Override
-  public boolean indexGroup(GroupIndexEvent event) {
-    return publisher.publishEvent(EventFamily.INDEX_EVENT, event);
-  }
-
-  @Override
-  public boolean deleteChangeFromIndex(ChangeIndexEvent event) {
-    return publisher.publishEvent(EventFamily.INDEX_EVENT, event);
-  }
-
-  @Override
-  public boolean indexProject(ProjectIndexEvent event) {
+  public boolean index(IndexEvent event) {
     return publisher.publishEvent(EventFamily.INDEX_EVENT, event);
   }
 }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexEventHandler.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexEventHandler.java
index 16eb9bb..9bef6fb 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexEventHandler.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexEventHandler.java
@@ -146,11 +146,7 @@
 
     @Override
     public void execute() {
-      if (changeIndexEvent.deleted) {
-        forwarders.forEach(f -> f.deleteChangeFromIndex(changeIndexEvent));
-      } else {
-        forwarders.forEach(f -> f.indexChange(changeIndexEvent));
-      }
+      forwarders.forEach(f -> f.index(changeIndexEvent));
     }
 
     @Override
@@ -182,7 +178,7 @@
 
     @Override
     public void execute() {
-      forwarders.forEach(f -> f.indexAccount(accountIndexEvent));
+      forwarders.forEach(f -> f.index(accountIndexEvent));
     }
 
     @Override
@@ -214,7 +210,7 @@
 
     @Override
     public void execute() {
-      forwarders.forEach(f -> f.indexGroup(groupIndexEvent));
+      forwarders.forEach(f -> f.index(groupIndexEvent));
     }
 
     @Override
@@ -246,7 +242,7 @@
 
     @Override
     public void execute() {
-      forwarders.forEach(f -> f.indexProject(projectIndexEvent));
+      forwarders.forEach(f -> f.index(projectIndexEvent));
     }
 
     @Override
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexModule.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexModule.java
index a9183d1..1f54385 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexModule.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/IndexModule.java
@@ -38,6 +38,8 @@
     DynamicSet.bind(binder(), GroupIndexedListener.class).to(IndexEventHandler.class);
     DynamicSet.bind(binder(), ProjectIndexedListener.class).to(IndexEventHandler.class);
 
+    bind(ProjectChecker.class).to(ProjectCheckerImpl.class);
+
     install(
         new FactoryModuleBuilder()
             .implement(ChangeChecker.class, ChangeCheckerImpl.class)
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectChecker.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectChecker.java
new file mode 100644
index 0000000..3fabbbd
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectChecker.java
@@ -0,0 +1,22 @@
+// Copyright (C) 2018 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.multisite.index;
+
+import com.google.gerrit.reviewdb.client.Project;
+
+/** Encapsulates the logic of verifying the up-to-date status of a project. */
+public interface ProjectChecker {
+  boolean isProjectUpToDate(Project.NameKey projectName);
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectCheckerImpl.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectCheckerImpl.java
new file mode 100644
index 0000000..606ff9d
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/index/ProjectCheckerImpl.java
@@ -0,0 +1,33 @@
+// Copyright (C) 2018 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.multisite.index;
+
+import com.google.gerrit.reviewdb.client.Project;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.inject.Inject;
+
+public class ProjectCheckerImpl implements ProjectChecker {
+  private final ProjectCache projectCache;
+
+  @Inject
+  ProjectCheckerImpl(ProjectCache projectCache) {
+    this.projectCache = projectCache;
+  }
+
+  @Override
+  public boolean isProjectUpToDate(Project.NameKey projectName) {
+    return projectCache.get(projectName) != null;
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/SourceAwareEventWrapper.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/SourceAwareEventWrapper.java
index 4f3a4d6..a618dfc 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/SourceAwareEventWrapper.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/SourceAwareEventWrapper.java
@@ -23,10 +23,10 @@
 
 public class SourceAwareEventWrapper {
 
-  private final KafkaEventHeader header;
+  private final EventHeader header;
   private final JsonObject body;
 
-  public KafkaEventHeader getHeader() {
+  public EventHeader getHeader() {
     return header;
   }
 
@@ -38,14 +38,13 @@
     return gsonProvider.get().fromJson(this.body, Event.class);
   }
 
-  public static class KafkaEventHeader {
+  public static class EventHeader {
     private final UUID eventId;
     private final String eventType;
     private final UUID sourceInstanceId;
     private final Long eventCreatedOn;
 
-    public KafkaEventHeader(
-        UUID eventId, String eventType, UUID sourceInstanceId, Long eventCreatedOn) {
+    public EventHeader(UUID eventId, String eventType, UUID sourceInstanceId, Long eventCreatedOn) {
       this.eventId = eventId;
       this.eventType = eventType;
       this.sourceInstanceId = sourceInstanceId;
@@ -90,7 +89,7 @@
     }
   }
 
-  public SourceAwareEventWrapper(KafkaEventHeader header, JsonObject body) {
+  public SourceAwareEventWrapper(EventHeader header, JsonObject body) {
     this.header = header;
     this.body = body;
   }
diff --git a/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/router/IndexEventRouter.java b/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/router/IndexEventRouter.java
index 63ec787..1f2a882 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/router/IndexEventRouter.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/multisite/kafka/router/IndexEventRouter.java
@@ -19,7 +19,6 @@
 
 import com.google.gerrit.reviewdb.client.Account;
 import com.google.gerrit.reviewdb.client.AccountGroup;
-import com.google.gerrit.reviewdb.client.Project;
 import com.google.gwtorm.server.OrmException;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
@@ -71,13 +70,11 @@
     } else if (sourceEvent instanceof GroupIndexEvent) {
       GroupIndexEvent groupIndexEvent = (GroupIndexEvent) sourceEvent;
       indexGroupHandler.index(
-          new AccountGroup.UUID(groupIndexEvent.groupUUID), INDEX, Optional.of(groupIndexEvent));
+          groupIndexEvent.groupUUID, INDEX, Optional.of(groupIndexEvent));
     } else if (sourceEvent instanceof ProjectIndexEvent) {
       ProjectIndexEvent projectIndexEvent = (ProjectIndexEvent) sourceEvent;
       indexProjectHandler.index(
-          new Project.NameKey(projectIndexEvent.projectName),
-          INDEX,
-          Optional.of(projectIndexEvent));
+          projectIndexEvent.projectName, INDEX, Optional.of(projectIndexEvent));
     } else {
       throw new UnsupportedOperationException(
           String.format("Cannot route event %s", sourceEvent.getType()));
diff --git a/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandlerTest.java b/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandlerTest.java
index d47643a..9013646 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandlerTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexGroupHandlerTest.java
@@ -43,20 +43,20 @@
   @Mock private Configuration config;
   @Mock private Configuration.Index index;
   private ForwardedIndexGroupHandler handler;
-  private AccountGroup.UUID uuid;
+  private String uuid;
 
   @Before
   public void setUp() throws Exception {
     when(config.index()).thenReturn(index);
     when(index.numStripedLocks()).thenReturn(10);
     handler = new ForwardedIndexGroupHandler(indexerMock, config);
-    uuid = new AccountGroup.UUID("123");
+    uuid = "123";
   }
 
   @Test
   public void testSuccessfulIndexing() throws Exception {
     handler.index(uuid, Operation.INDEX, Optional.empty());
-    verify(indexerMock).index(uuid);
+    verify(indexerMock).index(new AccountGroup.UUID(uuid));
   }
 
   @Test
@@ -77,13 +77,13 @@
                   return null;
                 })
         .when(indexerMock)
-        .index(uuid);
+        .index(new AccountGroup.UUID(uuid));
 
     assertThat(Context.isForwardedEvent()).isFalse();
     handler.index(uuid, Operation.INDEX, Optional.empty());
     assertThat(Context.isForwardedEvent()).isFalse();
 
-    verify(indexerMock).index(uuid);
+    verify(indexerMock).index(new AccountGroup.UUID(uuid));
   }
 
   @Test
@@ -95,7 +95,7 @@
                   throw new IOException("someMessage");
                 })
         .when(indexerMock)
-        .index(uuid);
+        .index(new AccountGroup.UUID(uuid));
 
     assertThat(Context.isForwardedEvent()).isFalse();
     try {
@@ -106,6 +106,6 @@
     }
     assertThat(Context.isForwardedEvent()).isFalse();
 
-    verify(indexerMock).index(uuid);
+    verify(indexerMock).index(new AccountGroup.UUID(uuid));
   }
 }
diff --git a/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandlerTest.java b/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandlerTest.java
index 6a76c48..9f94d5f 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandlerTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/multisite/forwarder/ForwardedIndexProjectHandlerTest.java
@@ -16,6 +16,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -24,8 +25,10 @@
 import com.google.gerrit.reviewdb.client.Project;
 import com.googlesource.gerrit.plugins.multisite.Configuration;
 import com.googlesource.gerrit.plugins.multisite.forwarder.ForwardedIndexingHandler.Operation;
+import com.googlesource.gerrit.plugins.multisite.index.ProjectChecker;
 import java.io.IOException;
 import java.util.Optional;
+import java.util.concurrent.ScheduledExecutorService;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -41,22 +44,29 @@
   @Rule public ExpectedException exception = ExpectedException.none();
   @Mock private ProjectIndexer indexerMock;
   @Mock private Configuration configMock;
+  @Mock private ProjectChecker projectCheckerMock;
   @Mock private Configuration.Index indexMock;
+  @Mock private ScheduledExecutorService indexExecutorMock;
   private ForwardedIndexProjectHandler handler;
-  private Project.NameKey nameKey;
+  private String nameKey;
 
   @Before
   public void setUp() {
     when(configMock.index()).thenReturn(indexMock);
     when(indexMock.numStripedLocks()).thenReturn(10);
-    handler = new ForwardedIndexProjectHandler(indexerMock, configMock);
-    nameKey = new Project.NameKey("project/name");
+    when(indexMock.retryInterval()).thenReturn(0);
+    when(indexMock.maxTries()).thenReturn(2);
+    when(projectCheckerMock.isProjectUpToDate(any())).thenReturn(true);
+    handler =
+        new ForwardedIndexProjectHandler(
+            indexerMock, projectCheckerMock, indexExecutorMock, configMock);
+    nameKey = "project/name";
   }
 
   @Test
   public void testSuccessfulIndexing() throws Exception {
     handler.index(nameKey, Operation.INDEX, Optional.empty());
-    verify(indexerMock).index(nameKey);
+    verify(indexerMock).index(new Project.NameKey(nameKey));
   }
 
   @Test
@@ -77,13 +87,13 @@
                   return null;
                 })
         .when(indexerMock)
-        .index(nameKey);
+        .index(new Project.NameKey(nameKey));
 
     assertThat(Context.isForwardedEvent()).isFalse();
     handler.index(nameKey, Operation.INDEX, Optional.empty());
     assertThat(Context.isForwardedEvent()).isFalse();
 
-    verify(indexerMock).index(nameKey);
+    verify(indexerMock).index(new Project.NameKey(nameKey));
   }
 
   @Test
@@ -95,7 +105,7 @@
                   throw new IOException("someMessage");
                 })
         .when(indexerMock)
-        .index(nameKey);
+        .index(new Project.NameKey(nameKey));
 
     assertThat(Context.isForwardedEvent()).isFalse();
     try {
@@ -106,6 +116,15 @@
     }
     assertThat(Context.isForwardedEvent()).isFalse();
 
-    verify(indexerMock).index(nameKey);
+    verify(indexerMock).index(new Project.NameKey(nameKey));
+  }
+
+  @Test
+  public void indexAttemptShouldFailWhenCheckerFails() throws Exception {
+    handler =
+        new ForwardedIndexProjectHandler(
+            indexerMock, (projectName) -> false, indexExecutorMock, configMock);
+
+    assertThat(handler.attemptIndex(nameKey, Optional.empty())).isFalse();
   }
 }
diff --git a/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/EventConsumerIT.java b/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/EventConsumerIT.java
index 98953bf..ea00251 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/EventConsumerIT.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/EventConsumerIT.java
@@ -44,7 +44,7 @@
     sysModule =
         "com.googlesource.gerrit.plugins.multisite.kafka.consumer.EventConsumerIT$KafkaTestContainerModule")
 public class EventConsumerIT extends LightweightPluginDaemonTest {
-  private static final int QUEUE_POLL_TIMEOUT_MSECS = 2000;
+  private static final int QUEUE_POLL_TIMEOUT_MSECS = 30000;
 
   public static class KafkaTestContainerModule extends LifecycleModule {
 
@@ -89,11 +89,12 @@
     drainQueue(droppedEventsQueue);
 
     createChange();
-    List<String> createdChangeEvents = receiveFromQueue(droppedEventsQueue, 2);
-    assertThat(createdChangeEvents).hasSize(2);
+    List<String> createdChangeEvents = receiveFromQueue(droppedEventsQueue, 3);
+    assertThat(createdChangeEvents).hasSize(3);
 
     assertThat(createdChangeEvents).contains("change-index");
     assertThat(createdChangeEvents).contains("ref-updated");
+    assertThat(createdChangeEvents).contains("patchset-created");
   }
 
   @Test
diff --git a/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/IndexEventRouterTest.java b/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/IndexEventRouterTest.java
index 71c3660..773c635 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/IndexEventRouterTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/multisite/kafka/consumer/IndexEventRouterTest.java
@@ -19,7 +19,6 @@
 
 import com.google.gerrit.reviewdb.client.Account;
 import com.google.gerrit.reviewdb.client.AccountGroup;
-import com.google.gerrit.reviewdb.client.Project;
 import com.googlesource.gerrit.plugins.multisite.forwarder.ForwardedIndexAccountHandler;
 import com.googlesource.gerrit.plugins.multisite.forwarder.ForwardedIndexChangeHandler;
 import com.googlesource.gerrit.plugins.multisite.forwarder.ForwardedIndexGroupHandler;
@@ -77,7 +76,7 @@
 
     verify(indexGroupHandler)
         .index(
-            new AccountGroup.UUID(groupId),
+            groupId,
             ForwardedIndexingHandler.Operation.INDEX,
             Optional.of(event));
 
@@ -91,10 +90,7 @@
     router.route(event);
 
     verify(indexProjectHandler)
-        .index(
-            Project.NameKey.parse(projectName),
-            ForwardedIndexingHandler.Operation.INDEX,
-            Optional.of(event));
+        .index(projectName, ForwardedIndexingHandler.Operation.INDEX, Optional.of(event));
 
     verifyZeroInteractions(indexAccountHandler, indexChangeHandler, indexGroupHandler);
   }