Merge branch 'stable-3.5' into stable-3.6

* stable-3.5:
  Format correctly Build file with buildifier
  Consume events-broker from source
  Skip web sessions replay for persisted cache

Change-Id: I877012c7414b6a02435cc4b52f91465a5f8e754c
diff --git a/BUILD b/BUILD
index f0fff60..87e21b0 100644
--- a/BUILD
+++ b/BUILD
@@ -1,24 +1,24 @@
 load("//tools/bzl:junit.bzl", "junit_tests")
 load(
     "//tools/bzl:plugin.bzl",
-    "gerrit_plugin",
     "PLUGIN_DEPS",
     "PLUGIN_TEST_DEPS",
+    "gerrit_plugin",
 )
 
 gerrit_plugin(
     name = "websession-broker",
     srcs = glob(["src/main/java/**/*.java"]),
-    resources = glob(["src/main/resources/**/*"]),
-    deps = [
-        "@events-broker//jar",
-    ],
     manifest_entries = [
         "Gerrit-PluginName: websession-broker",
         "Gerrit-HttpModule: com.googlesource.gerrit.plugins.websession.broker.BrokerBasedWebSession$Module",
         "Implementation-Title: Broker WebSession",
         "Implementation-URL: https://review.gerrithub.io/admin/repos/GerritForge/plugins_websession-broker",
     ],
+    resources = glob(["src/main/resources/**/*"]),
+    deps = [
+        ":events-broker-neverlink",
+    ],
 )
 
 junit_tests(
@@ -38,6 +38,12 @@
     exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
         ":websession-broker__plugin",
         "@mockito//jar",
-        "@events-broker//jar",
+        "//plugins/events-broker",
     ],
 )
+
+java_library(
+    name = "events-broker-neverlink",
+    neverlink = 1,
+    exports = ["//plugins/events-broker"],
+)
diff --git a/external_plugin_deps.bzl b/external_plugin_deps.bzl
index efe7780..1d8851b 100644
--- a/external_plugin_deps.bzl
+++ b/external_plugin_deps.bzl
@@ -15,12 +15,6 @@
     BYTE_BUDDY_VERSION = "1.9.10"
 
     maven_jar(
-        name = "events-broker",
-        artifact = "com.gerritforge:events-broker:3.5.0-alpha-202108041529",
-        sha1 = "309fe8cc08c46593d9990d4e5c448cc85e5a62b0",
-    )
-
-    maven_jar(
         name = "byte-buddy",
         artifact = "net.bytebuddy:byte-buddy:" + BYTE_BUDDY_VERSION,
         sha1 = "211a2b4d3df1eeef2a6cacf78d74a1f725e7a840",
diff --git a/src/main/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCache.java b/src/main/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCache.java
index d7255e2..dae6342 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCache.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCache.java
@@ -30,6 +30,7 @@
 import com.google.gerrit.httpd.WebSessionManager;
 import com.google.gerrit.httpd.WebSessionManager.Val;
 import com.google.gerrit.server.config.GerritInstanceId;
+import com.google.gerrit.server.config.GerritServerConfig;
 import com.google.gerrit.server.config.PluginConfigFactory;
 import com.google.gerrit.server.events.Event;
 import com.google.inject.Inject;
@@ -51,6 +52,7 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
+import org.eclipse.jgit.lib.Config;
 
 @Singleton
 public class BrokerBasedWebSessionCache
@@ -66,6 +68,7 @@
   ExecutorService executor;
   private final WebSessionLogger webSessionLogger;
   private String instanceId;
+  private final boolean shouldReplayAllSessions;
 
   @Inject
   public BrokerBasedWebSessionCache(
@@ -76,16 +79,22 @@
       @PluginName String pluginName,
       WebSessionLogger webSessionLogger,
       @WebSessionProducerExecutor ExecutorService executor,
-      @Nullable @GerritInstanceId String gerritInstanceId) {
+      @Nullable @GerritInstanceId String gerritInstanceId,
+      @GerritServerConfig Config gerritConfig) {
     this.cache = cache;
     this.brokerApi = brokerApi;
     this.timeMachine = timeMachine;
     this.webSessionTopicName = getWebSessionTopicName(cfg, pluginName);
+    this.shouldReplayAllSessions = shouldReplayAllSessions(gerritConfig);
     this.webSessionLogger = webSessionLogger;
     this.executor = executor;
     this.instanceId = gerritInstanceId;
   }
 
+  private Boolean shouldReplayAllSessions(Config gerritConfig) {
+    return gerritConfig.getInt("cache", "web_sessions", "diskLimit", 1024) == 0;
+  }
+
   protected void processMessage(Event message) {
     if (!WebSessionEvent.TYPE.equals(message.getType())) {
       logger.atWarning().log("Skipping web session message of unknown type: %s", message.getType());
@@ -231,7 +240,9 @@
       throw new IllegalStateException("Cannot find binding for BrokerApi");
     }
     brokerApi.get().receiveAsync(webSessionTopicName, this::processMessage);
-    brokerApi.get().replayAllEvents(webSessionTopicName);
+    if (shouldReplayAllSessions) {
+      brokerApi.get().replayAllEvents(webSessionTopicName);
+    }
   }
 
   @Override
diff --git a/src/main/resources/Documentation/build.md b/src/main/resources/Documentation/build.md
index d18e927..86b1063 100644
--- a/src/main/resources/Documentation/build.md
+++ b/src/main/resources/Documentation/build.md
@@ -6,6 +6,8 @@
 Clone (or link) this plugin to the `plugins` directory of Gerrit's
 source tree. Put the external dependency Bazel build file into
 the Gerrit /plugins directory, replacing the existing empty one.
+The plugin depends on [events-broker](https://gerrit.googlesource.com/modules/events-broker)
+which is linked directly from source with the same 'in-tree' plugin structure.
 
 ```
   cd gerrit/plugins
diff --git a/src/test/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCacheTest.java b/src/test/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCacheTest.java
index 833d0f8..ba7175d 100644
--- a/src/test/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCacheTest.java
+++ b/src/test/java/com/googlesource/gerrit/plugins/websession/broker/BrokerBasedWebSessionCacheTest.java
@@ -15,7 +15,10 @@
 package com.googlesource.gerrit.plugins.websession.broker;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -38,6 +41,7 @@
 import com.googlesource.gerrit.plugins.websession.broker.util.TimeMachine;
 import java.time.Instant;
 import java.util.concurrent.ExecutorService;
+import org.eclipse.jgit.lib.Config;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -76,6 +80,7 @@
   @Mock PluginConfigFactory cfg;
   @Mock PluginConfig pluginConfig;
   @Mock WebSessionLogger webSessionLogger;
+  @Mock Config gerritConfig;
   @Captor ArgumentCaptor<Event> eventCaptor;
   @Captor ArgumentCaptor<Val> valCaptor;
 
@@ -90,17 +95,8 @@
         .thenReturn("gerrit_web_session");
     when(cfg.getFromGerritConfig(PLUGIN_NAME)).thenReturn(pluginConfig);
     when(timeMachine.now()).thenReturn(Instant.EPOCH);
-    DynamicItem<BrokerApi> item = DynamicItem.itemOf(BrokerApi.class, brokerApi);
-    objectUnderTest =
-        new BrokerBasedWebSessionCache(
-            cache,
-            item,
-            timeMachine,
-            cfg,
-            PLUGIN_NAME,
-            webSessionLogger,
-            executorServce,
-            instanceId);
+
+    objectUnderTest = createBroker();
   }
 
   @Test
@@ -168,6 +164,53 @@
     assertThat(cache.getIfPresent(eventMessageKey(eventMessage))).isNull();
   }
 
+  @Test
+  public void shouldSkipSessionsReplayForPersistedCache() {
+    when(gerritConfig.getInt(eq("cache"), eq("web_sessions"), eq("diskLimit"), anyInt()))
+        .thenReturn(2048);
+    objectUnderTest = createBroker();
+
+    objectUnderTest.start();
+
+    verify(brokerApi, never()).replayAllEvents(anyString());
+  }
+
+  @Test
+  public void shouldReplaySessionsForInMemoryCache() {
+    when(gerritConfig.getInt(eq("cache"), eq("web_sessions"), eq("diskLimit"), anyInt()))
+        .thenReturn(0);
+
+    objectUnderTest = createBroker();
+
+    objectUnderTest.start();
+
+    verify(brokerApi, times(1)).replayAllEvents(anyString());
+  }
+
+  @Test
+  public void shouldSkipSessionsReplayForDefaultCacheSettings() {
+    when(gerritConfig.getInt(eq("cache"), eq("web_sessions"), eq("diskLimit"), anyInt()))
+        .thenReturn(1024);
+
+    objectUnderTest = createBroker();
+    objectUnderTest.start();
+    verify(brokerApi, never()).replayAllEvents(anyString());
+  }
+
+  private BrokerBasedWebSessionCache createBroker() {
+    DynamicItem<BrokerApi> item = DynamicItem.itemOf(BrokerApi.class, brokerApi);
+    return new BrokerBasedWebSessionCache(
+        cache,
+        item,
+        timeMachine,
+        cfg,
+        PLUGIN_NAME,
+        webSessionLogger,
+        executorServce,
+        instanceId,
+        gerritConfig);
+  }
+
   private Val createVal(Event message) {
     WebSessionEvent event = (WebSessionEvent) message;