Use always the last TS of the reindex across runs

Keep the last timestamp of the scanning loop and make sure that is
always used across different executions.

The writing of the last timestamp to the underlying file may have delays
whilst it is key to not perform useless reindexing while the file is
getting updated.

Change-Id: I80db1afa43874a82d9b723c6d3456dc7a8f65099
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/autoreindex/ReindexRunnable.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/autoreindex/ReindexRunnable.java
index bf4b607..fe76d71 100644
--- a/src/main/java/com/ericsson/gerrit/plugins/highavailability/autoreindex/ReindexRunnable.java
+++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/autoreindex/ReindexRunnable.java
@@ -35,6 +35,7 @@
   private final AbstractIndexRestApiServlet.IndexName itemName;
   private final OneOffRequestContext ctx;
   private final IndexTs indexTs;
+  private Timestamp newLastIndexTs;
 
   @Inject
   public ReindexRunnable(
@@ -49,9 +50,8 @@
     Optional<LocalDateTime> maybeIndexTs = indexTs.getUpdateTs(itemName);
     String itemNameString = itemName.name().toLowerCase();
     if (maybeIndexTs.isPresent()) {
-      Timestamp lastIndexTs = Timestamp.valueOf(maybeIndexTs.get());
-      Timestamp newLastIndexTs = lastIndexTs;
-      log.debug("Scanning for all the {}s after {}", itemNameString, lastIndexTs);
+      newLastIndexTs = maxTimestamp(newLastIndexTs, Timestamp.valueOf(maybeIndexTs.get()));
+      log.debug("Scanning for all the {}s after {}", itemNameString, newLastIndexTs);
       try (ManualRequestContext mctx = ctx.open();
           ReviewDb db = mctx.getReviewDbProvider().get()) {
         int count = 0;
@@ -59,12 +59,10 @@
         Stopwatch stopwatch = Stopwatch.createStarted();
         for (T c : fetchItems(db)) {
           try {
-            Optional<Timestamp> itemTs = indexIfNeeded(db, c, lastIndexTs);
+            Optional<Timestamp> itemTs = indexIfNeeded(db, c, newLastIndexTs);
             if (itemTs.isPresent()) {
               count++;
-              if (itemTs.get().after(newLastIndexTs)) {
-                newLastIndexTs = itemTs.get();
-              }
+              newLastIndexTs = maxTimestamp(newLastIndexTs, itemTs.get());
             }
           } catch (Exception e) {
             log.error("Unable to reindex {} {}", itemNameString, c, e);
@@ -92,6 +90,21 @@
     }
   }
 
+  private Timestamp maxTimestamp(Timestamp ts1, Timestamp ts2) {
+    if (ts1 == null) {
+      return ts2;
+    }
+
+    if (ts2 == null) {
+      return ts1;
+    }
+
+    if (ts1.after(ts2)) {
+      return ts1;
+    }
+    return ts2;
+  }
+
   protected abstract ResultSet<T> fetchItems(ReviewDb db) throws OrmException;
 
   protected abstract Optional<Timestamp> indexIfNeeded(ReviewDb db, T item, Timestamp sinceTs);