Initial implementation of events-nats plugin
- use NATS JetStream [1] to enable persistent streams to avoid loosing
messages if e.g. a Gerrit instance is restarted
- support synchronous and asynchronous publishing
- use durable push subscription [2] per Gerrit instanceId, in a cluster
setup we want messages to be delivered to each Gerrit instance
[1] https://docs.nats.io/nats-concepts/jetstream
[2] https://docs.nats.io/nats-concepts/jetstream/consumers
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..36693c4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.classpath
+.project
+/bin/
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..cd69ebd
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,52 @@
+load("//tools/bzl:junit.bzl", "junit_tests")
+load(
+ "//tools/bzl:plugin.bzl",
+ "PLUGIN_DEPS",
+ "PLUGIN_TEST_DEPS",
+ "gerrit_plugin",
+)
+
+gerrit_plugin(
+ name = "events-nats",
+ srcs = glob(["src/main/java/**/*.java"]),
+ manifest_entries = [
+ "Gerrit-PluginName: events-nats",
+ "Gerrit-InitStep: com.googlesource.gerrit.plugins.nats.InitConfig",
+ "Gerrit-Module: com.googlesource.gerrit.plugins.nats.Module",
+ "Implementation-Title: Gerrit NATS plugin",
+ "Implementation-URL: https://gerrit.googlesource.com/plugins/events-nats",
+ ],
+ resources = glob(["src/main/resources/**/*"]),
+ deps = [
+ "@events-broker//jar",
+ "@future-converter-java8-guava//jar",
+ "@future-converter-common//jar",
+ "@future-converter-java8-common//jar",
+ "@future-converter-guava-common//jar",
+ "@nats-client//jar",
+ ],
+)
+
+junit_tests(
+ name = "events_nats_tests",
+ srcs = glob(["src/test/java/**/*.java"]),
+ tags = ["events-nats"],
+ deps = [
+ ":events-nats__plugin_test_deps",
+ "@events-broker//jar",
+ "@nats-client//jar",
+ ],
+)
+
+java_library(
+ name = "events-nats__plugin_test_deps",
+ testonly = 1,
+ visibility = ["//visibility:public"],
+ exports = PLUGIN_DEPS + PLUGIN_TEST_DEPS + [
+ ":events-nats__plugin",
+ "@jackson-annotations//jar",
+ "@testcontainers//jar",
+ "@docker-java-api//jar",
+ "@docker-java-transport//jar",
+ ],
+)
diff --git a/Jenkinsfile b/Jenkinsfile
new file mode 100644
index 0000000..2e37583
--- /dev/null
+++ b/Jenkinsfile
@@ -0,0 +1,2 @@
+pluginPipeline(formatCheckId: 'gerritforge:plugins-events-nats-code-style',
+ buildCheckId: 'gerritforge:plugins-events-nats-build-test')
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..dd570dd
--- /dev/null
+++ b/README.md
@@ -0,0 +1,68 @@
+events-nats: Gerrit event producer for NATS
+=======================
+
+* Author: SAP SE
+* Repository: https://gerrit.googlesource.com/plugins/events-nats
+* CI/Release: https://gerrit-ci.gerritforge.com/search/?q=events-nats
+
+[![Build Status](https://gerrit-ci.gerritforge.com/job/plugin-events-nats-bazel-master/lastBuild/badge/icon)](https://gerrit-ci.gerritforge.com/job/plugin-events-nats-bazel-master/lastBuild/)
+
+Synopsis
+----------------------
+
+This plugins allows to define a distributed stream of events
+published by Gerrit.
+
+Events can be anything, from the traditional stream events
+to the Gerrit metrics.
+
+This plugin requires Gerrit 3.6 or later.
+
+Environments
+---------------------
+
+* `linux`
+* `java-11`
+* `Bazel`
+
+Build
+---------------------
+events-nats 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 events-nats plugin source directory into
+the /plugins path. Additionally, the plugins/external_plugin_deps.bzl file needs to be
+updated to match the events-nats plugin one.
+
+ git clone --recursive https://gerrit.googlesource.com/gerrit
+ git clone https://gerrit.googlesource.com/plugins/events-nats gerrit/plugins/events-nats
+ cd gerrit
+ rm plugins/external_plugin_deps.bzl
+ ln -s ./events-nats/external_plugin_deps.bzl plugins/.
+
+To build the events-nats plugins, issue the command from the Gerrit source path:
+
+ bazel build plugins/events-nats
+
+The output is created in
+
+ bazel-genfiles/plugins/events-nats/events-nats.jar
+
+Minimum Configuration
+---------------------
+Assuming a running NATS JetStream broker on the same Gerrit host, add the following
+settings to gerrit.config:
+
+```
+ [plugin "events-nats"]
+ server = nats://localhost:4222
+```
+
+Testing
+---------------------
+
+Starting a local NATS JetStream server for testing:
+
+```
+ docker run -d --name nats-main -p 4222:4222 -p 6222:6222 -p 8222:8222 nats -js
+```
+
+You can use the [NATS command line client](https://github.com/nats-io/natscli) to inspect and manage NATS.
diff --git a/external_plugin_deps.bzl b/external_plugin_deps.bzl
new file mode 100644
index 0000000..e52d5bc
--- /dev/null
+++ b/external_plugin_deps.bzl
@@ -0,0 +1,68 @@
+load("//tools/bzl:maven_jar.bzl", "maven_jar")
+
+def external_plugin_deps():
+ maven_jar(
+ name = "nats-client",
+ artifact = "io.nats:jnats:2.16.4",
+ sha1 = "dba5dd08f374d84cd54854610f9895abc2a19e80",
+ )
+
+ FUTURE_CONVERTER_VERSION = "1.2.0"
+
+ maven_jar(
+ name = "future-converter-java8-guava",
+ artifact = "net.javacrumbs.future-converter:future-converter-java8-guava:" + FUTURE_CONVERTER_VERSION,
+ sha1 = "9d6d59ee4e8f337ccf69ddd66e291a1ef77fbf4e",
+ )
+
+ maven_jar(
+ name = "future-converter-common",
+ artifact = "net.javacrumbs.future-converter:future-converter-common:" + FUTURE_CONVERTER_VERSION,
+ sha1 = "5fc7ea7c58ee0ce950e6104d5dda899f81959d7b",
+ )
+
+ maven_jar(
+ name = "future-converter-java8-common",
+ artifact = "net.javacrumbs.future-converter:future-converter-java8-common:" + FUTURE_CONVERTER_VERSION,
+ sha1 = "575932e773d58ddd459af417b2df31e2d07c4afc",
+ )
+
+ maven_jar(
+ name = "future-converter-guava-common",
+ artifact = "net.javacrumbs.future-converter:future-converter-guava-common:" + FUTURE_CONVERTER_VERSION,
+ sha1 = "b329c26e298bd77994cc2e304e4ac20da6f1569f",
+ )
+
+ TESTCONTAINERS_VERSION = "1.15.3"
+
+ maven_jar(
+ name = "testcontainers",
+ artifact = "org.testcontainers:testcontainers:" + TESTCONTAINERS_VERSION,
+ sha1 = "95c6cfde71c2209f0c29cb14e432471e0b111880",
+ )
+
+ DOCKER_JAVA_VERS = "3.2.8"
+
+ maven_jar(
+ name = "docker-java-api",
+ artifact = "com.github.docker-java:docker-java-api:" + DOCKER_JAVA_VERS,
+ sha1 = "4ac22a72d546a9f3523cd4b5fabffa77c4a6ec7c",
+ )
+
+ maven_jar(
+ name = "docker-java-transport",
+ artifact = "com.github.docker-java:docker-java-transport:" + DOCKER_JAVA_VERS,
+ sha1 = "c3b5598c67d0a5e2e780bf48f520da26b9915eab",
+ )
+
+ maven_jar(
+ name = "jackson-annotations",
+ artifact = "com.fasterxml.jackson.core:jackson-annotations:2.10.3",
+ sha1 = "0f63b3b1da563767d04d2e4d3fc1ae0cdeffebe7",
+ )
+
+ maven_jar(
+ name = "events-broker",
+ artifact = "com.gerritforge:events-broker:3.6.3",
+ sha1 = "2a78d4492810d5b4280c6a92e6b8bbdadaffe7d2",
+ )
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/Configuration.java b/src/main/java/com/googlesource/gerrit/plugins/nats/Configuration.java
new file mode 100644
index 0000000..b05ecdd
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/Configuration.java
@@ -0,0 +1,170 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.common.base.Strings;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.server.config.GerritInstanceId;
+import com.google.gerrit.server.config.GerritServerId;
+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 io.nats.client.JetStreamOptions;
+import io.nats.client.Options;
+import io.nats.client.PublishOptions;
+import io.nats.client.PushSubscribeOptions;
+import io.nats.client.api.AckPolicy;
+import io.nats.client.api.ConsumerConfiguration;
+import io.nats.client.api.DeliverPolicy;
+
+@Singleton
+class Configuration {
+ private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+ Options natsOptions;
+
+ private final boolean sendStreamEvents;
+ private final String streamName;
+ private final JetStreamOptions jetStreamOptions;
+ private final String streamEventsSubject;
+ private final boolean isPublishAsync;
+ private final PublishOptions publishOptions;
+ private final int publishThreads;
+ private final PushSubscribeOptions pushSubscribeOptions;
+ private final int shutdownTimeoutMs;
+
+ @Inject
+ public Configuration(
+ PluginConfigFactory configFactory,
+ @PluginName String pluginName,
+ @GerritServerId String gerritServerId,
+ @Nullable @GerritInstanceId String gerritInstanceId) {
+ PluginConfig pluginConfig = configFactory.getFromGerritConfig(pluginName);
+
+ sendStreamEvents = pluginConfig.getBoolean("sendStreamEvents", false);
+ streamName =
+ String.format("%s-%s", pluginConfig.getString("streamName", "gerrit"), gerritInstanceId);
+ isPublishAsync = pluginConfig.getBoolean("publishAsync", false);
+ streamEventsSubject =
+ getStringParam(pluginConfig, "streamEventsSubject", "gerrit_stream_events");
+ String[] serverList = getStringListParam(pluginConfig, "server");
+ if (serverList == null || serverList.length == 0) {
+ serverList = new String[] {"nats://localhost:4222"};
+ }
+ natsOptions = new Options.Builder().servers(serverList).build();
+ jetStreamOptions = new JetStreamOptions.Builder().build();
+ publishOptions = new PublishOptions.Builder().stream(streamEventsSubject).build();
+ publishThreads = pluginConfig.getInt("publishThreads", 1);
+ String consumerName = "consumer-" + gerritInstanceId;
+ pushSubscribeOptions =
+ ConsumerConfiguration.builder()
+ .durable(consumerName)
+ .ackPolicy(AckPolicy.Explicit)
+ .ackWait(pluginConfig.getInt("ackWaitMs", 60000))
+ .maxAckPending(pluginConfig.getLong("maxAckPending", 1000L))
+ .deliverPolicy(DeliverPolicy.All)
+ .buildPushSubscribeOptions();
+ shutdownTimeoutMs = pluginConfig.getInt("shutdownTimeoutMs", 1000);
+
+ logger.atInfo().log(
+ "NATS client configuration: sendStreamEvents: %b, streamEventsSubject: %s, natsOptions: %s, publishOptions: %s",
+ sendStreamEvents, streamEventsSubject, natsOptions, publishOptions);
+ }
+
+ private static String getStringParam(
+ PluginConfig pluginConfig, String name, String defaultValue) {
+ return Strings.isNullOrEmpty(System.getProperty(name))
+ ? pluginConfig.getString(name, defaultValue)
+ : System.getProperty(name);
+ }
+
+ private static String[] getStringListParam(PluginConfig pluginConfig, String name) {
+ return Strings.isNullOrEmpty(System.getProperty(name))
+ ? pluginConfig.getStringList(name)
+ : new String[] {System.getProperty(name)};
+ }
+
+ public Options getNatsOptions() {
+ return natsOptions;
+ }
+
+ /**
+ * Get the configured Nats publish options
+ *
+ * @return the configured Nats publish options
+ */
+ public PublishOptions getPublishOptions() {
+ return publishOptions;
+ }
+
+ /**
+ * Get the configured number of threads for publishing events to Nats
+ *
+ * @return the configured number of threads for publishing events to Nats
+ */
+ public int getPublishThreads() {
+ return publishThreads;
+ }
+
+ /**
+ * Whether stream-events should be published asynchronously
+ *
+ * @return whether stream-events should be published asynchronously
+ */
+ public Boolean isPublishAsync() {
+ return isPublishAsync;
+ }
+
+ /**
+ * Whether to publish stream-events
+ *
+ * @return whether to publish stream-events
+ */
+ public Boolean isSendStreamEvents() {
+ return sendStreamEvents;
+ }
+
+ public String getStreamName() {
+ return streamName;
+ }
+
+ public JetStreamOptions getJetStreamOptions() {
+ return jetStreamOptions;
+ }
+ /**
+ * Get the subject stream-events are published to
+ *
+ * @return subject stream-events are published to
+ */
+ public String getStreamEventsSubject() {
+ return streamEventsSubject;
+ }
+
+ /**
+ * Get the push subscribe options
+ *
+ * @return the push subscribe options
+ */
+ public PushSubscribeOptions getPushSubscribeOptions() {
+ return pushSubscribeOptions;
+ }
+
+ int getShutdownTimeoutMs() {
+ return shutdownTimeoutMs;
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/InitConfig.java b/src/main/java/com/googlesource/gerrit/plugins/nats/InitConfig.java
new file mode 100644
index 0000000..2e0fbc0
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/InitConfig.java
@@ -0,0 +1,93 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.pgm.init.api.ConsoleUI;
+import com.google.gerrit.pgm.init.api.InitStep;
+import com.google.gerrit.pgm.init.api.Section;
+import com.google.gerrit.server.config.GerritInstanceIdProvider;
+import com.google.inject.Inject;
+
+public class InitConfig implements InitStep {
+ private final Section pluginSection;
+ private final String pluginName;
+ private final ConsoleUI ui;
+ private final GerritInstanceIdProvider gerritInstanceIdProvider;
+
+ @Inject
+ InitConfig(
+ Section.Factory sections,
+ @PluginName String pluginName,
+ GerritInstanceIdProvider gerritInstanceIdProvider,
+ ConsoleUI ui) {
+ this.pluginName = pluginName;
+ this.ui = ui;
+ this.gerritInstanceIdProvider = gerritInstanceIdProvider;
+ this.pluginSection = sections.get("plugin", pluginName);
+ }
+
+ @Override
+ public void run() throws Exception {
+ ui.header(String.format("%s plugin", pluginName));
+
+ // pluginSection.string("AWS region (leave blank for default provider chain)", REGION_FIELD,
+ // null);
+ // pluginSection.string("AWS endpoint (dev or testing, not for production)", ENDPOINT_FIELD,
+ // null);
+
+ // boolean sendStreamEvents = ui.yesno(DEFAULT_SEND_STREAM_EVENTS, "Should send stream
+ // events?");
+ // pluginSection.set(SEND_STREAM_EVENTS_FIELD, Boolean.toString(sendStreamEvents));
+
+ // if (sendStreamEvents) {
+ // pluginSection.string(
+ // "Stream events topic", STREAM_EVENTS_TOPIC_FIELD, DEFAULT_STREAM_EVENTS_TOPIC);
+ // }
+ // pluginSection.string(
+ // "Number of subscribers", NUMBER_OF_SUBSCRIBERS_FIELD, DEFAULT_NUMBER_OF_SUBSCRIBERS);
+ // pluginSection.string("Application name", APPLICATION_NAME_FIELD, pluginName);
+ // pluginSection.string("Initial position", INITIAL_POSITION_FIELD, DEFAULT_INITIAL_POSITION);
+ // pluginSection.string(
+ // "Polling Interval (ms)",
+ // POLLING_INTERVAL_MS_FIELD,
+ // Long.toString(DEFAULT_POLLING_INTERVAL_MS));
+ // pluginSection.string(
+ // "Maximum number of record to fetch",
+ // MAX_RECORDS_FIELD,
+ // Integer.toString(DEFAULT_MAX_RECORDS));
+
+ // pluginSection.string(
+ // "Maximum total time waiting for a publish result (ms)",
+ // PUBLISH_SINGLE_REQUEST_TIMEOUT_MS_FIELD,
+ // Long.toString(DEFAULT_PUBLISH_SINGLE_REQUEST_TIMEOUT_MS));
+
+ // pluginSection.string(
+ // "Maximum total time waiting for publishing, including retries",
+ // PUBLISH_TIMEOUT_MS_FIELD,
+ // Long.toString(DEFAULT_PUBLISH_TIMEOUT_MS));
+
+ // pluginSection.string(
+ // "Maximum total time waiting when shutting down (ms)",
+ // SHUTDOWN_MS_FIELD,
+ // Long.toString(DEFAULT_SHUTDOWN_TIMEOUT_MS));
+ // pluginSection.string(
+ // "Which level AWS libraries should log at",
+ // AWS_LIB_LOG_LEVEL_FIELD,
+ // DEFAULT_AWS_LIB_LOG_LEVEL.toString());
+
+ // boolean sendAsync = ui.yesno(DEFAULT_SEND_ASYNC, "Should send messages asynchronously?");
+ // pluginSection.set(SEND_ASYNC_FIELD, Boolean.toString(sendAsync));
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/JetStreamManagementProvider.java b/src/main/java/com/googlesource/gerrit/plugins/nats/JetStreamManagementProvider.java
new file mode 100644
index 0000000..2d7dd95
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/JetStreamManagementProvider.java
@@ -0,0 +1,44 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import io.nats.client.Connection;
+import io.nats.client.JetStreamManagement;
+import java.io.IOException;
+import java.security.ProviderException;
+
+@Singleton
+public class JetStreamManagementProvider implements Provider<JetStreamManagement> {
+
+ private final Configuration config;
+ private final Connection connection;
+
+ @Inject
+ JetStreamManagementProvider(Configuration config, Connection connection) {
+ this.config = config;
+ this.connection = connection;
+ }
+
+ @Override
+ public JetStreamManagement get() {
+ try {
+ return connection.jetStreamManagement(config.getJetStreamOptions());
+ } catch (IOException e) {
+ throw new ProviderException(e);
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/Module.java b/src/main/java/com/googlesource/gerrit/plugins/nats/Module.java
new file mode 100644
index 0000000..bc2329f
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/Module.java
@@ -0,0 +1,78 @@
+// Copyright (C) 2022 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.nats;
+
+import static com.google.inject.Scopes.SINGLETON;
+
+import com.gerritforge.gerrit.eventbroker.BrokerApi;
+import com.gerritforge.gerrit.eventbroker.TopicSubscriber;
+import com.google.common.collect.Sets;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.gerrit.extensions.registration.DynamicItem;
+import com.google.gerrit.extensions.registration.DynamicSet;
+import com.google.gerrit.lifecycle.LifecycleModule;
+import com.google.gerrit.server.events.EventListener;
+import com.google.inject.Inject;
+import com.google.inject.TypeLiteral;
+import io.nats.client.Connection;
+import io.nats.client.JetStream;
+import io.nats.client.JetStreamManagement;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+
+public class Module extends LifecycleModule {
+ private final Configuration configuration;
+ private Set<TopicSubscriber> activeConsumers = Sets.newHashSet();
+
+ @Inject
+ Module(Configuration configuration) {
+ this.configuration = configuration;
+ }
+
+ /**
+ * By default the events-broker library (loaded directly by the multi-site) registers a noop
+ * implementation, which itself registers a list of topic subscribers. Since we have no control
+ * over which plugin is loaded first (multi-site or events-aws-kinesis), we deal with the
+ * possibility that a broker api was already registered and, in that case, reassign its consumers
+ * to the events-aws-kinesis plugin. The injection is optional because if the events-aws-kinesis
+ * plugin is loaded first, then there will be no previously registered broker API.
+ *
+ * @param previousBrokerApi
+ */
+ @Inject(optional = true)
+ public void setPreviousBrokerApi(DynamicItem<BrokerApi> previousBrokerApi) {
+ if (previousBrokerApi != null && previousBrokerApi.get() != null) {
+ this.activeConsumers = previousBrokerApi.get().topicSubscribers();
+ }
+ }
+
+ @Override
+ protected void configure() {
+ factory(NatsConsumer.Factory.class);
+ bind(ExecutorService.class)
+ .annotatedWith(PublishCallbackExecutor.class)
+ .toProvider(PublishCallbackExecutorProvider.class)
+ .in(SINGLETON);
+ bind(Connection.class).toProvider(NatsClientProvider.class).in(SINGLETON);
+ bind(JetStream.class).toProvider(NatsJetStreamProvider.class).in(SINGLETON);
+ bind(JetStreamManagement.class).toProvider(JetStreamManagementProvider.class);
+ bind(new TypeLiteral<Set<TopicSubscriber>>() {}).toInstance(activeConsumers);
+ DynamicItem.bind(binder(), BrokerApi.class).to(NatsBrokerApi.class).in(SINGLETON);
+ DynamicSet.bind(binder(), LifecycleListener.class).to(NatsBrokerLifeCycleManager.class);
+ if (configuration.isSendStreamEvents()) {
+ DynamicSet.bind(binder(), EventListener.class).to(NatsPublisher.class);
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerApi.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerApi.java
new file mode 100644
index 0000000..39b6400
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerApi.java
@@ -0,0 +1,72 @@
+// Copyright (C) 2022 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.nats;
+
+import com.gerritforge.gerrit.eventbroker.BrokerApi;
+import com.gerritforge.gerrit.eventbroker.TopicSubscriber;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.gerrit.server.events.Event;
+import com.google.inject.Inject;
+import java.util.Collections;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+class NatsBrokerApi implements BrokerApi {
+ private final NatsConsumer.Factory consumerFactory;
+
+ private final NatsPublisher publisher;
+ private final Set<NatsConsumer> consumers;
+
+ @Inject
+ public NatsBrokerApi(NatsPublisher publisher, NatsConsumer.Factory consumerFactory) {
+ this.publisher = publisher;
+ this.consumerFactory = consumerFactory;
+ this.consumers = Collections.newSetFromMap(new ConcurrentHashMap<>());
+ }
+
+ @Override
+ public ListenableFuture<Boolean> send(String streamName, Event event) {
+ return publisher.publish(streamName, event);
+ }
+
+ @Override
+ public void receiveAsync(String streamName, Consumer<Event> eventConsumer) {
+ NatsConsumer consumer = consumerFactory.create(streamName, eventConsumer);
+ consumers.add(consumer);
+ consumer.subscribe(streamName, eventConsumer);
+ }
+
+ @Override
+ public Set<TopicSubscriber> topicSubscribers() {
+ return consumers.stream()
+ .map(s -> TopicSubscriber.topicSubscriber(s.getStreamName(), s.getMessageProcessor()))
+ .collect(Collectors.toSet());
+ }
+
+ @Override
+ public void disconnect() {
+ consumers.parallelStream().forEach(NatsConsumer::shutdown);
+ consumers.clear();
+ }
+
+ @Override
+ public void replayAllEvents(String topic) {
+ consumers.stream()
+ .filter(subscriber -> topic.equals(subscriber.getStreamName()))
+ .forEach(NatsConsumer::resetOffset);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerLifeCycleManager.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerLifeCycleManager.java
new file mode 100644
index 0000000..7c286e0
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsBrokerLifeCycleManager.java
@@ -0,0 +1,101 @@
+// Copyright (C) 2022 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.nats;
+
+import com.gerritforge.gerrit.eventbroker.BrokerApi;
+import com.gerritforge.gerrit.eventbroker.TopicSubscriber;
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.extensions.events.LifecycleListener;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.nats.client.JetStreamApiException;
+import io.nats.client.JetStreamManagement;
+import io.nats.client.api.StorageType;
+import io.nats.client.api.StreamConfiguration;
+import io.nats.client.api.StreamInfo;
+import java.io.IOException;
+import java.security.ProviderException;
+import java.time.format.DateTimeFormatter;
+import java.util.Set;
+import java.util.logging.Level;
+
+@Singleton
+class NatsBrokerLifeCycleManager implements LifecycleListener {
+ private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+ private final Configuration config;
+ private final Set<TopicSubscriber> consumers;
+ private final BrokerApi brokerApi;
+ private JetStreamManagement jetStreamManagement;
+
+ @Inject
+ public NatsBrokerLifeCycleManager(
+ Configuration config,
+ JetStreamManagement jetStreamManagement,
+ Set<TopicSubscriber> consumers,
+ BrokerApi brokerApi) {
+ this.config = config;
+ this.jetStreamManagement = jetStreamManagement;
+ this.consumers = consumers;
+ this.brokerApi = brokerApi;
+ }
+
+ @Override
+ public void start() {
+ String streamName = config.getStreamName();
+ if (!streamExists(streamName)) {
+ try {
+ jetStreamManagement.addStream(
+ StreamConfiguration.builder()
+ .name(streamName)
+ .storageType(StorageType.File)
+ .addSubjects(config.getStreamEventsSubject())
+ .build());
+ logger.at(Level.INFO).log("Created new persistent NATS JetStream '%s'", streamName);
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (JetStreamApiException e) {
+ e.printStackTrace();
+ }
+ }
+ consumers.forEach(
+ topicSubscriber ->
+ brokerApi.receiveAsync(topicSubscriber.topic(), topicSubscriber.consumer()));
+ }
+
+ private boolean streamExists(String streamName) {
+ try {
+ StreamInfo info = jetStreamManagement.getStreamInfo(streamName);
+ logger.at(Level.INFO).log(
+ "NATS JetStream '%s' exists, description: '%s', created: '%s'",
+ streamName,
+ info.getDescription(),
+ info.getCreateTime().format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
+ return true;
+ } catch (JetStreamApiException e) {
+ if (e.getErrorCode() == 404) {
+ return false;
+ }
+ throw new ProviderException(e);
+ } catch (IOException e) {
+ throw new ProviderException(e);
+ }
+ }
+
+ @Override
+ public void stop() {
+ brokerApi.disconnect();
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsClientProvider.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsClientProvider.java
new file mode 100644
index 0000000..e0e01e1
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsClientProvider.java
@@ -0,0 +1,42 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import io.nats.client.Connection;
+import io.nats.client.Nats;
+import java.io.IOException;
+import java.security.ProviderException;
+
+@Singleton
+public class NatsClientProvider implements Provider<Connection> {
+
+ private final Configuration config;
+
+ @Inject
+ NatsClientProvider(Configuration config) {
+ this.config = config;
+ }
+
+ @Override
+ public Connection get() {
+ try {
+ return Nats.connect(config.getNatsOptions());
+ } catch (IOException | InterruptedException e) {
+ throw new ProviderException(e);
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsConsumer.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsConsumer.java
new file mode 100644
index 0000000..9d45d67
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsConsumer.java
@@ -0,0 +1,167 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.common.flogger.FluentLogger;
+import com.google.gerrit.server.events.Event;
+import com.google.inject.Inject;
+import io.nats.client.Connection;
+import io.nats.client.Dispatcher;
+import io.nats.client.JetStream;
+import io.nats.client.JetStreamApiException;
+import io.nats.client.JetStreamManagement;
+import io.nats.client.JetStreamSubscription;
+import io.nats.client.Message;
+import io.nats.client.MessageHandler;
+import io.nats.client.api.StreamConfiguration;
+import io.nats.client.api.StreamInfo;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.ProviderException;
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+
+// import software.amazon.kinesis.coordinator.Scheduler;
+
+class NatsConsumer {
+ interface Factory {
+ NatsConsumer create(String topic, Consumer<Event> messageProcessor);
+ }
+
+ private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+ private final Configuration config;
+
+ private java.util.function.Consumer<Event> messageProcessor;
+ private String streamName;
+ private AtomicBoolean resetOffset = new AtomicBoolean(false);
+ private final Connection connection;
+ private final JetStream jetStream;
+ private final JetStreamManagement jetStreamManagement;
+ private Dispatcher dispatcher;
+ private JetStreamSubscription subscription;
+
+ @Inject
+ public NatsConsumer(
+ Configuration config,
+ Connection connection,
+ JetStream jetStream,
+ JetStreamManagement jetStreamManagement) {
+ this.config = config;
+ this.connection = connection;
+ this.dispatcher = connection.createDispatcher();
+ this.jetStream = jetStream;
+ this.jetStreamManagement = jetStreamManagement;
+ }
+
+ public void subscribe(String streamName, java.util.function.Consumer<Event> messageProcessor) {
+ this.streamName = streamName;
+ this.messageProcessor = messageProcessor;
+ String subject = getOrCreateSubject(streamName);
+ logger.atInfo().log("NATS consumer - subscribe to subject [%s]", streamName);
+ runReceiver(messageProcessor, subject);
+ }
+
+ private String getOrCreateSubject(String name) {
+ try {
+ StreamInfo stream = jetStreamManagement.getStreamInfo(config.getStreamName());
+ StreamConfiguration sc = stream.getConfiguration();
+ List<String> subjects = sc.getSubjects();
+ if (!subjects.stream().anyMatch(n -> n.equals(name))) {
+ addSubject(sc, name);
+ }
+ return name;
+ } catch (IOException | JetStreamApiException e) {
+ throw new ProviderException(e);
+ }
+ }
+
+ private void addSubject(StreamConfiguration sc, String name)
+ throws IOException, JetStreamApiException {
+ List<String> subjects = sc.getSubjects();
+ subjects.add(name);
+ sc = StreamConfiguration.builder(sc).subjects(subjects).build();
+ jetStreamManagement.updateStream(sc);
+ logger.atInfo().log(
+ "NATS consumer - added subject [%s] to stream [%s], subjects: [%s]",
+ name, sc.getName(), subjects);
+ }
+
+ private void runReceiver(java.util.function.Consumer<Event> messageProcessor, String subject) {
+ try {
+ this.subscription =
+ jetStream.subscribe(
+ subject,
+ dispatcher,
+ new MessageHandler() {
+
+ @Override
+ public void onMessage(Message msg) throws InterruptedException {
+ Event e = new Event(new String(msg.getData(), StandardCharsets.UTF_8)) {};
+ messageProcessor.accept(e);
+ msg.ack();
+ logger.atFine().log("NATS consumer - consumed and acked event '%s'", e);
+ }
+ },
+ false);
+ } catch (IOException | JetStreamApiException e) {
+ logger.atSevere().withCause(e).log(
+ "NATS consumer - subscribing to subject [%s] failed", subject);
+ }
+ }
+
+ public void shutdown() {
+ try {
+ int shutdownTimeoutMs = config.getShutdownTimeoutMs();
+ Duration shutdownTimeout = Duration.ofMillis(shutdownTimeoutMs);
+ logger.atInfo().log(
+ "NATS consumer - Waiting up to '%s' milliseconds to complete shutdown of consumer of stream '%s'",
+ shutdownTimeoutMs, getStreamName());
+ connection.closeDispatcher(dispatcher);
+ CompletableFuture<Boolean> f = connection.drain(shutdownTimeout);
+ connection.flush(shutdownTimeout);
+ f.get(shutdownTimeoutMs, TimeUnit.MILLISECONDS);
+ connection.close();
+ } catch (Exception e) {
+ logger.atSevere().withCause(e).log(
+ "NATS consumer - error caught when shutting down consumer for stream %s",
+ getStreamName());
+ }
+ logger.atInfo().log(
+ "NATS consumer - shutdown consumer of stream %s completed.", getStreamName());
+ }
+
+ public java.util.function.Consumer<Event> getMessageProcessor() {
+ return messageProcessor;
+ }
+
+ public String getStreamName() {
+ return streamName;
+ }
+
+ public void resetOffset() {
+ // Move all checkpoints (if any) to TRIM_HORIZON, so that the consumer
+ // scheduler will start consuming from beginning.
+ // checkpointResetter.setAllShardsToBeginning(streamName);
+
+ // Even when no checkpoints have been persisted, instruct the consumer
+ // scheduler to start from TRIM_HORIZON, irrespective of 'initialPosition'
+ // configuration.
+ resetOffset.set(true);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsJetStreamProvider.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsJetStreamProvider.java
new file mode 100644
index 0000000..351ba1f
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsJetStreamProvider.java
@@ -0,0 +1,43 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import io.nats.client.Connection;
+import io.nats.client.JetStream;
+import java.io.IOException;
+import java.security.ProviderException;
+
+@Singleton
+public class NatsJetStreamProvider implements Provider<JetStream> {
+
+ private Connection connection;
+
+ @Inject
+ public NatsJetStreamProvider(Connection connection) {
+ this.connection = connection;
+ }
+
+ @Override
+ public JetStream get() {
+ try {
+ return connection.jetStream();
+ } catch (IOException e) {
+ throw new ProviderException(e);
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/NatsPublisher.java b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsPublisher.java
new file mode 100644
index 0000000..607f103
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/NatsPublisher.java
@@ -0,0 +1,109 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.common.flogger.FluentLogger;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.gerrit.server.events.Event;
+import com.google.gerrit.server.events.EventGson;
+import com.google.gerrit.server.events.EventListener;
+import com.google.gson.Gson;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.nats.client.JetStream;
+import io.nats.client.JetStreamApiException;
+import io.nats.client.api.PublishAck;
+import io.nats.client.impl.NatsMessage;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.ExecutorService;
+import net.javacrumbs.futureconverter.java8guava.FutureConverter;
+
+@Singleton
+class NatsPublisher implements EventListener {
+ private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+ private final JetStream jetStream;
+ private final Configuration configuration;
+ private final Gson gson;
+ private final ExecutorService callBackExecutor;
+
+ @Inject
+ public NatsPublisher(
+ @EventGson Gson gson,
+ Configuration configuration,
+ JetStream jetStream,
+ @PublishCallbackExecutor ExecutorService callBackExecutor) {
+ this.gson = gson;
+ this.jetStream = jetStream;
+ this.configuration = configuration;
+ this.callBackExecutor = callBackExecutor;
+ }
+
+ @Override
+ public void onEvent(Event event) {
+ String subject = configuration.getStreamEventsSubject();
+ publish(subject, event);
+ logger.atFine().log("NATS publisher - Successfully published Gerrit stream-event '%s'", event);
+ }
+
+ ListenableFuture<Boolean> publish(String subject, Event event) {
+ NatsMessage msg =
+ NatsMessage.builder()
+ .subject(subject)
+ .data(gson.toJson(event), StandardCharsets.UTF_8)
+ .build();
+ return configuration.isPublishAsync() ? publishAsync(msg) : publishSync(msg);
+ }
+
+ private ListenableFuture<Boolean> publishAsync(NatsMessage msg) {
+ try {
+ ListenableFuture<PublishAck> f =
+ FutureConverter.toListenableFuture(jetStream.publishAsync(msg));
+
+ Futures.addCallback(
+ f,
+ new FutureCallback<PublishAck>() {
+ @Override
+ public void onSuccess(PublishAck result) {
+ logger.atFine().log("NATS publisher - Successfully published event '%s'", msg);
+ }
+
+ @Override
+ public void onFailure(Throwable e) {
+ logger.atSevere().withCause(e).log(
+ "NATS publisher - Failed publishing event %s", msg);
+ }
+ },
+ callBackExecutor);
+
+ return Futures.transform(f, res -> !res.hasError(), callBackExecutor);
+ } catch (Exception e) {
+ logger.atSevere().withCause(e).log("NATS publisher - Error when publishing event %s", msg);
+ return Futures.immediateFailedFuture(e);
+ }
+ }
+
+ private ListenableFuture<Boolean> publishSync(NatsMessage msg) {
+ try {
+ return Futures.immediateFuture(!jetStream.publish(msg).hasError());
+ } catch (IOException | JetStreamApiException e) {
+ logger.atSevere().withCause(e).log("NATS publisher - Failed publishing event : %s", msg);
+ return Futures.immediateFailedFuture(e);
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutor.java b/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutor.java
new file mode 100644
index 0000000..677baf4
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutor.java
@@ -0,0 +1,24 @@
+// 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.nats;
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import com.google.inject.BindingAnnotation;
+import java.lang.annotation.Retention;
+
+@Retention(RUNTIME)
+@BindingAnnotation
+public @interface PublishCallbackExecutor {}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutorProvider.java b/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutorProvider.java
new file mode 100644
index 0000000..7f74d26
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/nats/PublishCallbackExecutorProvider.java
@@ -0,0 +1,40 @@
+// Copyright (C) 2022 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.nats;
+
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import com.google.gerrit.server.logging.LoggingContextAwareExecutorService;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+class PublishCallbackExecutorProvider implements Provider<ExecutorService> {
+
+ private final Configuration configuration;
+
+ @Inject
+ PublishCallbackExecutorProvider(Configuration configuration) {
+ this.configuration = configuration;
+ }
+
+ @Override
+ public ExecutorService get() {
+ return new LoggingContextAwareExecutorService(
+ Executors.newFixedThreadPool(
+ configuration.getPublishThreads(),
+ new ThreadFactoryBuilder().setNameFormat("nats-publish-callback-executor-%d").build()));
+ }
+}