diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..14700a2 --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,38 @@ +name-template: '$RESOLVED_VERSION' +tag-template: '$RESOLVED_VERSION' +prerelease: true +template: | + # What's Changed + + $CHANGES +categories: + - title: Breaking + label: breaking + - title: New + label: enhancement + - title: Bug Fixes + label: bug + - title: Maintenance + label: maintenance + - title: Documentation + label: documentation + - title: Dependency Updates + label: dependencies + +version-resolver: + major: + labels: + - breaking + minor: + labels: + - enhancement + patch: + labels: + - bug + - maintenance + - documentation + - dependencies + - security + +exclude-labels: + - skip-changelog diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..82f63b4 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,35 @@ +name: Build + +on: + pull_request: + branches: [ master ] + +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '8' + + - uses: actions/cache@v4 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-cache-${{ hashFiles('**/*.gradle.kts') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - uses: actions/cache@v4 + with: + path: ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradlew- + + - run: | + chmod +x gradlew + ./gradlew build diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 0000000..fef8afa --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,16 @@ +name: Update Changelog + +on: + push: + branches: [ master ] + +jobs: + changelog: + name: Update Changelog + runs-on: ubuntu-latest + if: ${{ !contains(github.event.head_commit.message, 'skip-snapshot') }} + steps: + - uses: release-drafter/release-drafter@master + id: release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml new file mode 100644 index 0000000..3603af2 --- /dev/null +++ b/.github/workflows/snapshot.yml @@ -0,0 +1,41 @@ +name: Update Snapshot +on: + push: + branches: + - master +jobs: + snapshot: + name: Update Snapshot + runs-on: ubuntu-latest + if: "${{ !contains(github.event.head_commit.message, 'skip-snapshot') }}" + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: 'adopt' + java-version: '8' + + - uses: actions/cache@v4 + with: + path: ~/.gradle/caches + key: ${{ runner.os }}-gradle-cache-${{ hashFiles('**/*.gradle.kts') }} + restore-keys: | + ${{ runner.os }}-gradle- + + - uses: actions/cache@v4 + with: + path: ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradlew- + + - uses: crazy-max/ghaction-import-gpg@v6.1.0 + with: + gpg_private_key: "${{ secrets.GPG_PRIVATE_KEY }}" + passphrase: "${{ secrets.GPG_PASSPHRASE }}" + + - run: | + [[ "${{ steps.release.outputs.tag_name }}" =~ ^[0-9]+(\.[0-9]+)*$ ]] || exit -1 + chmod +x gradlew + ./gradlew -Psign-required=true publishToSonatype closeAndReleaseSonatypeStagingRepository -Pversion="${{ steps.release.outputs.tag_name }}-SNAPSHOT" -PinfumiaSigningKey="${{ secrets.GPG_SECRET_KEY_ID }}" -PinfumiaSigningPassword="${{ secrets.GPG_PASSPHRASE }}" -PsonatypeUsername="${{ secrets.SONATYPE_USERNAME }}" -PsonatypePassword="${{ secrets.SONATYPE_PASSWORD }}" diff --git a/.gitignore b/.gitignore index 524f096..c27cedb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,24 +1,10 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* +.idea/ +target/ +.gradle/ +build/ +*.iml +*.project +*.classpath +.settings/ +**/bin/ +.vscode/ diff --git a/README.md b/README.md index d774bdf..7231df2 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,38 @@ # pubsub -Simplified pubsub library for Redis and various databases. +![Sonatype Nexus (Releases)](https://img.shields.io/nexus/r/tr.com.infumia/pubsub?label=maven-central&server=https%3A%2F%2Foss.sonatype.org%2F) +![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/tr.com.infumia/pubsub?label=maven-central&server=https%3A%2F%2Foss.sonatype.org) +## How to Use (Developers) +### Code +```groovy +repositories { + maven("https://jitpack.io/") +} + +dependencies { + // Base module + implementation "tr.com.infumia:pubsub:VERSION" + // Required, https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine/ + implementation "com.github.ben-manes.caffeine:caffeine:2.9.3" // for java-8+ + implementation "com.github.ben-manes.caffeine:caffeine:3.1.8" // for java-11+ + + // Pub/Sub using Redis (Optional) + implementation "tr.com.infumia:pubsub-redis:VERSION" + // Required, https://mvnrepository.com/artifact/io.lettuce/lettuce-core/ + implementation "io.lettuce:lettuce-core:6.3.2.RELEASE" + + // Kotlin extensions (Optional) + implementation "tr.com.infumia:pubsub-kotlin:VERSION" + + // Kotlin protobuf serializer (Optional) + implementation "tr.com.infumia:pubsub-kotlin-protobuf:VERSION" + // Required, https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-reflect/ + implementation "org.jetbrains.kotlin:kotlin-reflect:2.0.0" + // Required, https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-serialization-core/ + implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.7.0" + // Required, https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-serialization-protobuf/ + implementation "org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.7.0" +} +``` +```java +void pubsub() {} +``` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..a415a7b --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,29 @@ +plugins { + java + alias(libs.plugins.indra.publishing.sonatype) +} + +repositories.mavenCentral() + +subprojects { + apply() + + repositories.mavenCentral() + + java { + toolchain { + languageVersion = JavaLanguageVersion.of(8) + } + } + + tasks { + compileJava { + options.compilerArgs.add("-Xlint:-processing") + options.compilerArgs.add("-Xlint:-options") + } + } +} + +indraSonatype { + useAlternateSonatypeOSSHost("s01") +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..bf43e04 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + java + `kotlin-dsl` +} + +repositories { + mavenCentral() + gradlePluginPortal() +} + +dependencies { + implementation(libs.indra) +} diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 0000000..105225c --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,9 @@ +dependencyResolutionManagement { + versionCatalogs { + create("libs") { + from(files("../gradle/libs.versions.toml")) + } + } +} + +rootProject.name = "buildSrc" diff --git a/buildSrc/src/main/kotlin/tr.com.infumia.pubsub.build.publishing.gradle.kts b/buildSrc/src/main/kotlin/tr.com.infumia.pubsub.build.publishing.gradle.kts new file mode 100644 index 0000000..6cffae7 --- /dev/null +++ b/buildSrc/src/main/kotlin/tr.com.infumia.pubsub.build.publishing.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("net.kyori.indra") + id("net.kyori.indra.publishing") +} + +val projectName = project.property("artifact-id") as String + +indra { + mitLicense() + github("infumia", "pubsub") + configurePublications { + artifactId = projectName + + pom { + name = projectName + inceptionYear = "2024" + description = "Simplified pubsub library for Redis and various databases." + developers { + developer { + name = "Hasan Demirtaş" + url = "https://github.com/portlek/" + } + } + organization { + name = "Infumia" + url = "https://github.com/infumia/" + } + } + } + if (project.hasProperty("sign-required")) { + signWithKeyFromPrefixedProperties("infumia") + } +} diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 0000000..5e64f68 --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + id("tr.com.infumia.pubsub.build.publishing") +} + +dependencies { + compileOnly(libs.caffeine) +} diff --git a/common/gradle.properties b/common/gradle.properties new file mode 100644 index 0000000..36d7d3d --- /dev/null +++ b/common/gradle.properties @@ -0,0 +1 @@ +artifact-id=pubsub diff --git a/common/src/main/java/tr/com/infumia/pubsub/AwaitingResponder.java b/common/src/main/java/tr/com/infumia/pubsub/AwaitingResponder.java new file mode 100644 index 0000000..e0aa8ac --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/AwaitingResponder.java @@ -0,0 +1,21 @@ +package tr.com.infumia.pubsub; + +import java.time.Duration; +import java.util.concurrent.CompletableFuture; + +final class AwaitingResponder { + private final CompletableFuture future = new CompletableFuture<>(); + final Class responseType; + + AwaitingResponder(final Class responseType) { + this.responseType = responseType; + } + + void complete(final T response) { + this.future.complete(response); + } + + CompletableFuture await(final Duration timeout) { + return Internal.delay(this.future, timeout); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Broker.java b/common/src/main/java/tr/com/infumia/pubsub/Broker.java new file mode 100644 index 0000000..9ad918e --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Broker.java @@ -0,0 +1,160 @@ +package tr.com.infumia.pubsub; + +import java.time.Duration; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * The interface for a message broker that supports sending, receiving, and responding to messages. + */ +public interface Broker extends AutoCloseable { + /** + * Initializes the message broker. + */ + void initialize(); + + /** + * Sends a message to the specified targets. + *

+ * Sends to {@link Target#global()} if {@code targets} is not specified. + * + * @param message the message to send. Cannot be {@code null} + * @param targets the targets to send the message to. Cannot be {@code null} + */ + void send(Object message, Collection targets); + + /** + * Sends a message to the specified targets. + *

+ * Sends to {@link Target#global()} if {@code targets} is not specified. + * + * @param message the message to send. Cannot be {@code null} + * @param targets the targets to send the message to. Can be empty, cannot be {@code null} + */ + default void send(final Object message, final Target... targets) { + this.send(message, Arrays.asList(targets)); + } + + /** + * Listens for messages using a handler. + * + * @param handler the handler to process incoming messages. Cannot be {@code null} + * @return an {@link AutoCloseable} to stop listening. Cannot be {@code null} + */ + AutoCloseable listen(Handler handler); + + /** + * Listens for messages of a specific type using a consumer. + * + * @param type the class object representing the type {@link T}. Cannot be {@code null} + * @param handler the consumer to process incoming messages. Cannot be {@code null} + * @param the type of the message to listen for. + * @return an {@link AutoCloseable} to stop listening. Cannot be {@code null} + */ + default AutoCloseable listen(final Class type, final Consumer handler) { + return this.listen(new Handler() { + @Override + public Class type() { + return type; + } + + @Override + public void handle(final T t) { + handler.accept(t); + } + }); + } + + /** + * Sends a request to targets and awaits a response within a timeout. + * + * @param message the request message. Cannot be {@code null} + * @param responseType the class object representing the response type {@link R}. Cannot be {@code null} + * @param timeout the duration to wait for a response. Cannot be {@code null} + * @param targets the targets to send the request to. Cannot be {@code null} + * @param the type of the response. + * @return a {@link CompletableFuture} representing the response. Cannot be {@code null} + */ + CompletableFuture request(Object message, Class responseType, Duration timeout, + Collection targets); + + /** + * Sends a request and awaits a response within a timeout. + * + * @param message the request message. Cannot be {@code null} + * @param responseType the class object representing the response type {@link R}. Cannot be {@code null} + * @param timeout the duration to wait for a response. Cannot be {@code null} + * @param targets the targets to send the request to. Can be empty, cannot be {@code null} + * @param the type of the response. + * @return a {@link CompletableFuture} representing the response. Cannot be {@code null} + */ + default CompletableFuture request(final Object message, final Class responseType, final Duration timeout, + final Target... targets) { + return this.request(message, responseType, timeout, Arrays.asList(targets)); + } + + /** + * Sends a request and awaits a response using the default timeout. + * + * @param message the request message. Cannot be {@code null} + * @param responseType the class object representing the response type {@link R}. Cannot be {@code null} + * @param targets the targets to send the request to. Can be empty, cannot be {@code null} + * @param the type of the response. + * @return a {@link CompletableFuture} representing the response. Cannot be {@code null} + */ + default CompletableFuture request(final Object message, final Class responseType, + final Target... targets) { + return this.request(message, responseType, Internal.REQUEST_TIMEOUT, targets); + } + + /** + * Sends a request to targets and awaits a response using the default timeout. + * + * @param message the request message. Cannot be {@code null} + * @param responseType the class object representing the response type {@link R}. Cannot be {@code null} + * @param targets the targets to send the request to. Cannot be {@code null} + * @param the type of the response. + * @return a {@link CompletableFuture} representing the response. Cannot be {@code null} + */ + default CompletableFuture request(final Object message, final Class responseType, + final Collection targets) { + return this.request(message, responseType, Internal.REQUEST_TIMEOUT, targets); + } + + /** + * Registers a responder to handle requests of a specific type. + * + * @param responder the responder to handle requests. Cannot be {@code null} + * @return an {@link AutoCloseable} to stop responding. Cannot be {@code null} + */ + AutoCloseable respond(Responder responder); + + /** + * Registers a function to respond to requests of a specific type. + * + * @param type the class object representing the type {@link T}. Cannot be {@code null} + * @param responder the function to handle requests and produce responses. Cannot be {@code null} + * @param the type of the request message. + * @param the type of the response. + * @return an {@link AutoCloseable} to stop responding. Cannot be {@code null} + */ + default AutoCloseable respond(final Class type, final Function responder) { + return this.respond(new Responder() { + @Override + public Class type() { + return type; + } + + @Override + public Y handle(final T t) { + return responder.apply(t); + } + }); + } + + @Override + void close(); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/BrokerStringAbstract.java b/common/src/main/java/tr/com/infumia/pubsub/BrokerStringAbstract.java new file mode 100644 index 0000000..3b2deb3 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/BrokerStringAbstract.java @@ -0,0 +1,164 @@ +package tr.com.infumia.pubsub; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +import java.time.Duration; +import java.util.Collection; +import java.util.Collections; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * Abstract class for a message broker that operates with strings and supports sending, receiving, and responding to messages. + */ +public abstract class BrokerStringAbstract implements Broker { + private final UUID brokerId = UUID.randomUUID(); + private final HandlerRegistry handlerRegistry = new HandlerRegistry(); + protected final Target responderTarget = Internal.responderTarget(this.brokerId); + private final Cache> awaitingResponders = Caffeine.newBuilder() + .expireAfterWrite(Internal.RESPOND_TIMEOUT) + .build(); + + private final CodecProvider codecProvider; + + /** + * Ctor. + * + * @param codecProvider the CodecProvider used for encoding and decoding messages. Cannot be {@code null}. + */ + protected BrokerStringAbstract(final CodecProvider codecProvider) { + this.codecProvider = codecProvider; + } + + @Override + public final void initialize() { + this.connect(); + } + + @Override + public final void send(final Object message, final Collection targets) { + this.sendEnvelope( + Internal.newEnvelope(this.codecProvider, this.brokerId, message), + this.channelsForMessage(message, targets) + ); + } + + @Override + public final AutoCloseable listen(final Handler handler) { + return this.respond(new HandlerToResponder<>(handler)); + } + + @Override + public final CompletableFuture request(final Object message, final Class responseType, final Duration timeout, final Collection targets) { + final Envelope envelope = Internal.newEnvelope(this.codecProvider, this.brokerId, message); + final AwaitingResponder responder = new AwaitingResponder<>(responseType); + this.awaitingResponders.put(envelope.messageId, responder); + this.sendEnvelope(envelope, this.channelsForMessage(message, targets)); + return responder.await(timeout); + } + + @Override + public final AutoCloseable respond(final Responder responder) { + return this.handlerRegistry.register(this.messageTypeId(responder.type()), responder); + } + + @Override + public void close() { + this.handlerRegistry.close(); + } + + /** + * Calls registered handlers based on the provided channel and encoded data. + * + * @param channel the channel from which the message was received. Cannot be {@code null}. + * @param encodedData the encoded data representing the message. Cannot be {@code null}. + */ + protected final void callHandlers(final String channel, final String encodedData) { + final Envelope envelope = this.codecProvider.provide(Envelope.class).decode(Hex.decode(encodedData)); + if (envelope.respondsTo != null) { + this.handleResponderEnvelope(envelope); + return; + } + final Collection> responders = this.handlerRegistry.get(this.messageTypeIdForChannel(channel)); + if (responders == null) { + return; + } + for (final Responder responder : responders) { + final Envelope response = this.handleEnvelope(envelope, responder); + if (response != null) { + final Collection previousChannel = this.channelsForMessage( + responder, + Collections.singleton(Internal.responderTarget(envelope.brokerId)) + ); + this.sendEnvelope(response, previousChannel); + } + } + } + + /** + * Establishes a connection to the message broker. + */ + protected abstract void connect(); + + /** + * Determines the channels to which a message should be sent based on the message type ID and target collection. + * + * @param messageTypeId the ID of the message type. Cannot be {@code null}. + * @param targets the collection of targets to which the message should be sent. Cannot be {@code null}. + * @return a collection of channel names. Cannot be {@code null}. + */ + protected abstract Collection channelsFor(String messageTypeId, Collection targets); + + /** + * Retrieves the message type ID for the specified channel. + * + * @param channel the name of the channel. Cannot be {@code null}. + * @return the message type ID associated with the channel. Cannot be {@code null}. + */ + protected abstract String messageTypeIdForChannel(String channel); + + /** + * Sends serialized data to the specified channels. + * + * @param channels the collection of channels to which the data should be sent. Cannot be {@code null}. + * @param serializedData the serialized data to send. Cannot be {@code null}. + */ + protected abstract void sendData(Collection channels, String serializedData); + + private void sendEnvelope(final Envelope envelope, final Collection channels) { + this.sendData(channels, Hex.encode(this.codecProvider.provide(Envelope.class).encode(envelope))); + } + + private void handleResponderEnvelope(final Envelope envelope) { + final AwaitingResponder responder = this.awaitingResponders.getIfPresent(envelope.respondsTo); + if (responder != null) { + this.handleResponderEnvelope(envelope, responder); + } + } + + private void handleResponderEnvelope(final Envelope envelope, final AwaitingResponder responder) { + responder.complete(this.codecProvider.provide(responder.responseType).decode(envelope.messagePayload)); + } + + private Envelope handleEnvelope( + final Envelope envelope, + final Responder responder + ) { + final T decoded = this.codecProvider.provide(responder.type()).decode(envelope.messagePayload); + final Y response = responder.handle(decoded); + if (response == null) { + return null; + } else { + return Internal.newRespondingEnvelope(this.codecProvider, this.brokerId, envelope, response); + } + } + + private Collection channelsForMessage(final Object message, final Collection targets) { + return this.channelsFor(this.messageTypeId(message.getClass()), targets); + } + + private String messageTypeId(final Class messageType) { + return messageType.toString(); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Codec.java b/common/src/main/java/tr/com/infumia/pubsub/Codec.java new file mode 100644 index 0000000..dae6f1a --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Codec.java @@ -0,0 +1,24 @@ +package tr.com.infumia.pubsub; + +/** + * The interface for encoding and decoding objects of type {@link T} to and from byte arrays. + * + * @param the type of the object to be encoded and decoded. + */ +public interface Codec { + /** + * Encodes an object of type {@link T} into a byte array. + * + * @param t the object to encode. + * @return a byte array representing the encoded object. + */ + byte[] encode(T t); + + /** + * Decodes a byte array into an object of type {@link T}. + * + * @param bytes the byte array to decode. + * @return the decoded object. + */ + T decode(byte[] bytes); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/CodecProvider.java b/common/src/main/java/tr/com/infumia/pubsub/CodecProvider.java new file mode 100644 index 0000000..b5ef540 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/CodecProvider.java @@ -0,0 +1,15 @@ +package tr.com.infumia.pubsub; + +/** + * The interface for providing {@link Codec} instances based on the class type. + */ +public interface CodecProvider { + /** + * Provides a {@link Codec} instance for the specified class type. + * + * @param type the class object representing the type {@code T} + * @param the type of the object for which the codec is to be provided + * @return a {@link Codec} for the specified class type + */ + Codec provide(Class type); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/CodecProviderCached.java b/common/src/main/java/tr/com/infumia/pubsub/CodecProviderCached.java new file mode 100644 index 0000000..7a2f647 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/CodecProviderCached.java @@ -0,0 +1,28 @@ +package tr.com.infumia.pubsub; + +import java.util.HashMap; +import java.util.Map; + +/** + * A cached implementation of the {@link CodecProvider} interface. + */ +public final class CodecProviderCached implements CodecProvider { + private final Map, Codec> cache = new HashMap<>(); + private final CodecProvider delegate; + + /** + * Ctor. + * + * @param delegate the delegate {@link CodecProvider} used to provide codecs. + */ + public CodecProviderCached(final CodecProvider delegate) { + this.delegate = delegate; + } + + @Override + @SuppressWarnings("unchecked") + public Codec provide(final Class type) { + return (Codec) this.cache.computeIfAbsent(type, __ -> + this.delegate.provide(type)); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Envelope.java b/common/src/main/java/tr/com/infumia/pubsub/Envelope.java new file mode 100644 index 0000000..ce5781f --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Envelope.java @@ -0,0 +1,47 @@ +package tr.com.infumia.pubsub; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +final class Envelope { + final UUID brokerId; + final UUID messageId; + /** + * Can be {@code null}. + */ + final UUID respondsTo; + final byte[] messagePayload; + + Envelope( + final UUID brokerId, + final UUID messageId, + final UUID respondsTo, + final byte[] messagePayload + ) { + this.brokerId = brokerId; + this.messageId = messageId; + this.respondsTo = respondsTo; + this.messagePayload = messagePayload; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || this.getClass() != o.getClass()) { + return false; + } + final Envelope envelope = (Envelope) o; + return Objects.equals(this.brokerId, envelope.brokerId) && + Objects.equals(this.messageId, envelope.messageId) && + Objects.equals(this.respondsTo, envelope.respondsTo) && + Objects.deepEquals(this.messagePayload, envelope.messagePayload); + } + + @Override + public int hashCode() { + return Objects.hash(this.brokerId, this.messageId, this.respondsTo, Arrays.hashCode(this.messagePayload)); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Handler.java b/common/src/main/java/tr/com/infumia/pubsub/Handler.java new file mode 100644 index 0000000..be35f7f --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Handler.java @@ -0,0 +1,22 @@ +package tr.com.infumia.pubsub; + +/** + * The interface for handling Pub/Sub messages of type {@link T}. + * + * @param the type of the message to be handled. + */ +public interface Handler { + /** + * Retrieves the class type of the message being handled. + * + * @return the {@link Class} object representing the type {@link T}. + */ + Class type(); + + /** + * Handles a message of type {@link T} received from Pub/Sub. + * + * @param t the message to handle. + */ + void handle(T t); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/HandlerRegistry.java b/common/src/main/java/tr/com/infumia/pubsub/HandlerRegistry.java new file mode 100644 index 0000000..1958076 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/HandlerRegistry.java @@ -0,0 +1,51 @@ +package tr.com.infumia.pubsub; + +import java.util.Collection; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +final class HandlerRegistry { + private final ReentrantLock lock = new ReentrantLock(); + private final MultiMap> handlers = new MultiMap<>(); + + void close() { + this.withLock(this.handlers::clear); + } + + AutoCloseable register(final String messageTypeId, final Responder handler) { + this.withLock(() -> this.handlers.put(messageTypeId, handler)); + return () -> this.unregister(messageTypeId, handler); + } + + void unregister(final String messageTypeId, final Responder handler) { + this.withLock(() -> this.handlers.remove(messageTypeId, handler)); + } + + Collection> get(final String messageTypeId) { + return this.withLock(() -> { + final Collection> handlers = this.handlers.get(messageTypeId); + if (handlers == null || handlers.isEmpty()) { + return null; + } + return handlers; + }); + } + + private T withLock(final Supplier task) { + this.lock.lock(); + try { + return task.get(); + } finally { + this.lock.unlock(); + } + } + + private void withLock(final Runnable task) { + this.lock.lock(); + try { + task.run(); + } finally { + this.lock.unlock(); + } + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/HandlerToResponder.java b/common/src/main/java/tr/com/infumia/pubsub/HandlerToResponder.java new file mode 100644 index 0000000..43578c9 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/HandlerToResponder.java @@ -0,0 +1,20 @@ +package tr.com.infumia.pubsub; + +final class HandlerToResponder implements Responder { + private final Handler delegate; + + HandlerToResponder(final Handler delegate) { + this.delegate = delegate; + } + + @Override + public Class type() { + return this.delegate.type(); + } + + @Override + public Object handle(final T t) { + this.delegate.handle(t); + return null; + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Hex.java b/common/src/main/java/tr/com/infumia/pubsub/Hex.java new file mode 100644 index 0000000..2653fb9 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Hex.java @@ -0,0 +1,85 @@ +/* + * Copyright 2017 Patrick Favre-Bulle + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 tr.com.infumia.pubsub; + +import java.util.Objects; + +/** + * From + */ +final class Hex { + private static final char[] LOOKUP_TABLE_LOWER = new char[]{0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66}; + + static String encode(final byte[] byteArray) { + final char[] buffer = new char[byteArray.length * 2]; + final char[] lookup = Hex.LOOKUP_TABLE_LOWER; + + for (int i = 0; i < byteArray.length; i++) { + buffer[i << 1] = lookup[(byteArray[i] >> 4) & 0xF]; + buffer[(i << 1) + 1] = lookup[(byteArray[i] & 0xF)]; + } + return new String(buffer); + } + + static byte[] decode(final CharSequence hexString) { + int start; + if (Objects.requireNonNull(hexString).length() > 2 && + hexString.charAt(0) == '0' && hexString.charAt(1) == 'x') { + start = 2; + } else { + start = 0; + } + + final int len = hexString.length(); + final boolean isOddLength = len % 2 != 0; + if (isOddLength) { + start--; + } + + final byte[] data = new byte[(len - start) / 2]; + int first4Bits; + int second4Bits; + for (int i = start; i < len; i += 2) { + if (i == start && isOddLength) { + first4Bits = 0; + } else { + first4Bits = Character.digit(hexString.charAt(i), 16); + } + second4Bits = Character.digit(hexString.charAt(i + 1), 16); + + if (first4Bits == -1 || second4Bits == -1) { + if (i == start && isOddLength) { + throw new IllegalArgumentException("'" + hexString.charAt(i + 1) + "' at index " + (i + 1) + " is not hex formatted"); + } else { + throw new IllegalArgumentException("'" + hexString.charAt(i) + hexString.charAt(i + 1) + "' at index " + i + " is not hex formatted"); + } + } + + data[(i - start) / 2] = (byte) ((first4Bits << 4) + second4Bits); + } + return data; + } + + private Hex() { + throw new IllegalStateException("Utility class"); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Internal.java b/common/src/main/java/tr/com/infumia/pubsub/Internal.java new file mode 100644 index 0000000..870bc83 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Internal.java @@ -0,0 +1,72 @@ +package tr.com.infumia.pubsub; + +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +final class Internal { + private static final ScheduledExecutorService DELAYER = Executors.newScheduledThreadPool(1); + static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(10L); + static final Duration RESPOND_TIMEOUT = Duration.ofMinutes(1L); + + static CompletableFuture delay( + final CompletableFuture future, + final Duration timeout + ) { + if (future.isDone()) { + return future; + } + final ScheduledFuture delay = Internal.DELAYER.schedule( + () -> future.completeExceptionally(new TimeoutException()), + timeout.toMillis(), + TimeUnit.MILLISECONDS + ); + return future.whenComplete((__, ___) -> { + if (!delay.isDone()) { + delay.cancel(false); + } + }); + } + + @SuppressWarnings("unchecked") + static Envelope newEnvelope( + final CodecProvider codecProvider, + final UUID brokerId, + final Object payload + ) { + return new Envelope( + brokerId, + UUID.randomUUID(), + null, + codecProvider.provide((Class) payload.getClass()).encode(payload) + ); + } + + @SuppressWarnings("unchecked") + static Envelope newRespondingEnvelope( + final CodecProvider codecProvider, + final UUID brokerId, + final Envelope request, + final Object response + ) { + return new Envelope( + brokerId, + UUID.randomUUID(), + request.messageId, + codecProvider.provide((Class) response.getClass()).encode(response) + ); + } + + static Target responderTarget(final UUID brokerId) { + return Target.of("_BROKER", brokerId.toString()); + } + + private Internal() { + throw new IllegalStateException("Utility class"); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Lazy.java b/common/src/main/java/tr/com/infumia/pubsub/Lazy.java new file mode 100644 index 0000000..c833ae8 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Lazy.java @@ -0,0 +1,32 @@ +package tr.com.infumia.pubsub; + +import java.util.function.Supplier; + +final class Lazy implements Supplier { + static Lazy of(final Supplier supplier) { + return new Lazy<>(supplier); + } + + private final Supplier supplier; + + private volatile T value; + + private Lazy(final Supplier supplier) { + this.supplier = supplier; + } + + @Override + public T get() { + T val = this.value; + if (val == null) { + synchronized (this) { + val = this.value; + if (val == null) { + val = this.supplier.get(); + this.value = val; + } + } + } + return val; + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/MultiMap.java b/common/src/main/java/tr/com/infumia/pubsub/MultiMap.java new file mode 100644 index 0000000..84670b3 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/MultiMap.java @@ -0,0 +1,36 @@ +package tr.com.infumia.pubsub; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +final class MultiMap { + private final Map> map = new HashMap<>(); + + MultiMap() {} + + void put(final K key, final V value) { + this.map.computeIfAbsent(key, __ -> new HashSet<>()).add(value); + } + + Collection get(final K key) { + return this.map.get(key); + } + + boolean remove(final K key, final V value) { + final Collection values = this.map.get(key); + if (values == null) { + return false; + } + final boolean removed = values.remove(value); + if (values.isEmpty()) { + this.map.remove(key); + } + return removed; + } + + void clear() { + this.map.clear(); + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Responder.java b/common/src/main/java/tr/com/infumia/pubsub/Responder.java new file mode 100644 index 0000000..eb91cf7 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Responder.java @@ -0,0 +1,25 @@ +package tr.com.infumia.pubsub; + +/** + * The interface for handling Pub/Sub messages of type {@code T} and providing a response of type {@code Y}. + * + * @param the type of the message to be handled. + * @param the type of the response. + */ +public interface Responder { + + /** + * Retrieves the class type of the message being handled. + * + * @return the {@link Class} object representing the type {@link T}. + */ + Class type(); + + /** + * Handles a message of type {@link T} received from Pub/Sub and provides a response of type {@link Y}. + * + * @param t the message to handle. + * @return the response of type {@link Y}. + */ + Y handle(T t); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/Target.java b/common/src/main/java/tr/com/infumia/pubsub/Target.java new file mode 100644 index 0000000..8296c09 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/Target.java @@ -0,0 +1,40 @@ +package tr.com.infumia.pubsub; + +/** + * The interface represents message targets. + */ +public interface Target { + /** + * Creates a target from {@code type} and {@code identifier}. + * + * @param type the type of the target. + * @param identifier the identifier of the target. + * @return a newly created message target. + */ + static Target of(final String type, final String identifier) { + return new TargetImpl(type, identifier); + } + + /** + * Creates a global target for the message that will be published to all subscribers. + * + * @return a newly created global message target. + */ + static Target global() { + return TargetImpl.GLOBAL; + } + + /** + * Returns type of the target. + * + * @return type of the target. + */ + String type(); + + /** + * Returns identifier of the target. + * + * @return identifier of the target. + */ + String identifier(); +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/TargetImpl.java b/common/src/main/java/tr/com/infumia/pubsub/TargetImpl.java new file mode 100644 index 0000000..b328f0d --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/TargetImpl.java @@ -0,0 +1,23 @@ +package tr.com.infumia.pubsub; + +final class TargetImpl implements Target { + static final Target GLOBAL = Target.of("", ""); + + private final String type; + private final String identifier; + + TargetImpl(final String type, final String identifier) { + this.type = type; + this.identifier = identifier; + } + + @Override + public String type() { + return this.type; + } + + @Override + public String identifier() { + return this.identifier; + } +} diff --git a/common/src/main/java/tr/com/infumia/pubsub/TargetProvider.java b/common/src/main/java/tr/com/infumia/pubsub/TargetProvider.java new file mode 100644 index 0000000..570e276 --- /dev/null +++ b/common/src/main/java/tr/com/infumia/pubsub/TargetProvider.java @@ -0,0 +1,36 @@ +package tr.com.infumia.pubsub; + +import java.util.Arrays; +import java.util.Collection; + +/** + * The interface for providing {@link Target}s. + */ +public interface TargetProvider { + /** + * Creates a non-dynamic target provider. + * + * @param targets the targets to create. + * @return a newly created target provider. + */ + static TargetProvider of(final Collection targets) { + return () -> targets; + } + + /** + * Creates a non-dynamic target provider. + * + * @param targets the targets to create. + * @return a newly created target provider. + */ + static TargetProvider of(final Target... targets) { + return TargetProvider.of(Arrays.asList(targets)); + } + + /** + * Provides the message targets. + * + * @return the message targets. Can be {@code null}. + */ + Collection provide(); +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..ee79197 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +name=pubsub +group=tr.com.infumia +version=1.0.0-SNAPSHOT + +org.gradle.parallel=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..5a4906a --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,19 @@ +[versions] +kotlin = "2.0.0" +kotlinserialization = "1.7.0" +indra = "3.1.3" + +[libraries] +caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version = "2.9.3" } +redis = { module = "io.lettuce:lettuce-core", version = "6.3.2.RELEASE" } +kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } +kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinserialization" } +kotlinx-serialization-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "kotlinserialization" } + +indra = { module = "net.kyori:indra-common", version.ref = "indra" } + +[plugins] +kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +dokka = { id = "org.jetbrains.dokka", version = "1.9.20" } +indra-publishing-sonatype = { id = "net.kyori.indra.publishing.sonatype", version.ref = "indra" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6f7a6eb --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/kotlin/extensions/build.gradle.kts b/kotlin/extensions/build.gradle.kts new file mode 100644 index 0000000..03d94b2 --- /dev/null +++ b/kotlin/extensions/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + alias(libs.plugins.kotlin) + alias(libs.plugins.dokka) + id("tr.com.infumia.pubsub.build.publishing") +} + +dependencies { + compileOnly(project(":common")) +} + +tasks { + javadocJar { + from(dokkaJavadoc.map { it.outputs }) + } +} diff --git a/kotlin/extensions/gradle.properties b/kotlin/extensions/gradle.properties new file mode 100644 index 0000000..03c31f9 --- /dev/null +++ b/kotlin/extensions/gradle.properties @@ -0,0 +1 @@ +artifact-id=pubsub-kotlin diff --git a/kotlin/extensions/src/main/kotlin/tr/com/infumia/pubsub/BrokerExtension.kt b/kotlin/extensions/src/main/kotlin/tr/com/infumia/pubsub/BrokerExtension.kt new file mode 100644 index 0000000..543c370 --- /dev/null +++ b/kotlin/extensions/src/main/kotlin/tr/com/infumia/pubsub/BrokerExtension.kt @@ -0,0 +1,35 @@ +package tr.com.infumia.pubsub + +import java.util.concurrent.CompletableFuture + +/** + * Registers a handler to listen for messages of a specific type. + * + * @param handler the function to handle incoming messages of type [T]. + * @param T the type of the message to listen for. + * @return an [AutoCloseable] that can be used to unregister the handler. + */ +inline fun Broker.listen(noinline handler: (T) -> Unit): AutoCloseable = + listen(T::class.java, handler) + +/** + * Sends a message and expects a response of a specific type. + * + * @param message the message to send. + * @param targets the targets to send the message to. + * @param R the type of the expected response. + * @return a [CompletableFuture] representing the response to the message. + */ +inline fun Broker.request(message: Any, vararg targets: Target): CompletableFuture = + request(message, R::class.java, *targets) + +/** + * Registers a function to respond to messages of a specific type. + * + * @param handler the function to handle incoming messages of type [T] and produce a response of type [R]. + * @param T the type of the message to respond to. + * @param R the type of the response. + * @return an [AutoCloseable] that can be used to unregister the responder. + */ +inline fun Broker.respond(noinline handler: (T) -> R?): AutoCloseable = + respond(T::class.java, handler) diff --git a/kotlin/protobuf/build.gradle.kts b/kotlin/protobuf/build.gradle.kts new file mode 100644 index 0000000..cd88b36 --- /dev/null +++ b/kotlin/protobuf/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { + alias(libs.plugins.kotlin) + alias(libs.plugins.kotlin.serialization) + alias(libs.plugins.dokka) + id("tr.com.infumia.pubsub.build.publishing") +} + +dependencies { + compileOnly(project(":common")) + + compileOnly(libs.kotlin.reflect) + compileOnly(libs.kotlinx.serialization.core) + compileOnly(libs.kotlinx.serialization.protobuf) +} + +tasks { + javadocJar { + from(dokkaJavadoc.map { it.outputs }) + } +} diff --git a/kotlin/protobuf/gradle.properties b/kotlin/protobuf/gradle.properties new file mode 100644 index 0000000..524d8d3 --- /dev/null +++ b/kotlin/protobuf/gradle.properties @@ -0,0 +1 @@ +artifact-id=pubsub-kotlin-protobuf diff --git a/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodec.kt b/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodec.kt new file mode 100644 index 0000000..6f3fcd1 --- /dev/null +++ b/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodec.kt @@ -0,0 +1,16 @@ +package tr.com.infumia.pubsub + +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.protobuf.ProtoBuf + +@OptIn(ExperimentalSerializationApi::class) +internal class ProtobufCodec( + private val serializer: KSerializer +) : Codec { + override fun encode(message: T): ByteArray = + ProtoBuf.encodeToByteArray(serializer, message) + + override fun decode(message: ByteArray): T = + ProtoBuf.decodeFromByteArray(serializer, message) +} diff --git a/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodecProvider.kt b/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodecProvider.kt new file mode 100644 index 0000000..21df040 --- /dev/null +++ b/kotlin/protobuf/src/main/kotlin/tr/com/infumia/pubsub/ProtobufCodecProvider.kt @@ -0,0 +1,14 @@ +package tr.com.infumia.pubsub + +import kotlin.reflect.full.createType +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.protobuf.ProtoBuf +import kotlinx.serialization.serializer + +@Suppress("UNCHECKED_CAST") +@OptIn(ExperimentalSerializationApi::class) +class ProtobufCodecProvider : CodecProvider { + override fun provide(type: Class): Codec = + ProtobufCodec(ProtoBuf.serializersModule.serializer(type.kotlin.createType()) as KSerializer) +} diff --git a/redis/build.gradle.kts b/redis/build.gradle.kts new file mode 100644 index 0000000..5bc15fb --- /dev/null +++ b/redis/build.gradle.kts @@ -0,0 +1,9 @@ +plugins { + id("tr.com.infumia.pubsub.build.publishing") +} + +dependencies { + compileOnly(project(":common")) + + compileOnly(libs.redis) +} diff --git a/redis/gradle.properties b/redis/gradle.properties new file mode 100644 index 0000000..e0ce7b0 --- /dev/null +++ b/redis/gradle.properties @@ -0,0 +1 @@ +artifact-id=pubsub-redis diff --git a/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedis.java b/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedis.java new file mode 100644 index 0000000..29a4567 --- /dev/null +++ b/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedis.java @@ -0,0 +1,119 @@ +package tr.com.infumia.pubsub; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.pubsub.RedisPubSubAdapter; +import io.lettuce.core.pubsub.StatefulRedisPubSubConnection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.stream.Collectors; + +/** + * Abstract class for a Redis-based message broker. + */ +public abstract class BrokerRedis extends BrokerStringAbstract { + private final Lazy> channelPrefixes; + private final RedisClientProvider clientProvider; + + private StatefulRedisConnection publishConnection; + private StatefulRedisPubSubConnection subscribeConnection; + + /** + * Ctor. + * + * @param codecProvider the CodecProvider used for encoding and decoding messages. Cannot be null. + * @param clientProvider the RedisClientProvider used for obtaining Redis client connections. Cannot be null. + */ + public BrokerRedis(final CodecProvider codecProvider, final RedisClientProvider clientProvider) { + super(codecProvider); + this.clientProvider = clientProvider; + this.channelPrefixes = Lazy.of(() -> { + final ArrayList channels = new ArrayList<>(); + channels.addAll(Internal.channelPrefixFor(Collections.emptySet())); + channels.addAll(Internal.channelPrefixFor(Collections.singleton(this.responderTarget))); + final TargetProvider targetProvider = this.targetProvider(); + if (targetProvider != null) { + final Collection targets = targetProvider.provide(); + if (targets != null) { + channels.addAll(Internal.channelPrefixFor(targets)); + } + } + return channels; + }); + } + + @Override + protected void connect() { + final RedisClient client = this.clientProvider.provide(); + this.publishConnection = client.connect(); + this.subscribeConnection = client.connectPubSub(); + + this.subscribeConnection.addListener(new RedisPubSubAdapter() { + @Override + public void message(final String pattern, final String channel, final String message) { + BrokerRedis.this.callHandlers(channel, message); + } + }); + this.subscribeConnection.sync().psubscribe(this.channelPrefixes.get().toArray(new String[0])); + } + + @Override + protected Collection channelsFor(final String messageTypeId, final Collection targets) { + return Internal.channelPrefixFor(targets).stream() + .map(s -> s + messageTypeId) + .collect(Collectors.toList()); + } + + @Override + protected String messageTypeIdForChannel(final String channel) { + final String prefix = this.channelPrefixes.get().stream() + .filter(channel::startsWith) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No channel prefix found for " + channel)); + return channel.substring(prefix.length()); + } + + @Override + protected void sendData(final Collection channels, final String serializedData) { + for (final String channel : channels) { + this.publishConnection.sync().publish(channel, serializedData); + } + } + + @Override + public void close() { + super.close(); + this.publishConnection.close(); + this.subscribeConnection.close(); + } + + /** + * Provides the target provider used to determine target channels. + * + * @return the target provider instance. Can be {@code null}. + */ + protected abstract TargetProvider targetProvider(); + + private static final class Internal { + private static final String CHANNEL_PREFIX = "Messaging:"; + private static final String GLOBAL_PREFIX = "Global:"; + private static final String TARGET_PREFIX = "Target:"; + + private static Collection channelPrefixFor(final Collection targets) { + if (targets.isEmpty()) { + return Collections.singletonList(Internal.CHANNEL_PREFIX + Internal.GLOBAL_PREFIX); + } + return targets.stream() + .map(target -> + Internal.CHANNEL_PREFIX + + Internal.TARGET_PREFIX + + target.type() + + ":" + + target.identifier() + ) + .collect(Collectors.toList()); + } + } +} diff --git a/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedisNoTargetProvider.java b/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedisNoTargetProvider.java new file mode 100644 index 0000000..bb1025d --- /dev/null +++ b/redis/src/main/java/tr/com/infumia/pubsub/BrokerRedisNoTargetProvider.java @@ -0,0 +1,21 @@ +package tr.com.infumia.pubsub; + +/** + * A concrete implementation of {@link BrokerRedis} that does not provide a target provider. + */ +public final class BrokerRedisNoTargetProvider extends BrokerRedis { + /** + * Ctor. + * + * @param codecProvider the CodecProvider used for encoding and decoding messages. + * @param clientProvider the RedisClientProvider used for obtaining Redis client connections. + */ + public BrokerRedisNoTargetProvider(final CodecProvider codecProvider, final RedisClientProvider clientProvider) { + super(codecProvider, clientProvider); + } + + @Override + protected TargetProvider targetProvider() { + return null; + } +} diff --git a/redis/src/main/java/tr/com/infumia/pubsub/RedisClientProvider.java b/redis/src/main/java/tr/com/infumia/pubsub/RedisClientProvider.java new file mode 100644 index 0000000..a412a3e --- /dev/null +++ b/redis/src/main/java/tr/com/infumia/pubsub/RedisClientProvider.java @@ -0,0 +1,15 @@ +package tr.com.infumia.pubsub; + +import io.lettuce.core.RedisClient; + +/** + * The interface for providing {@link RedisClient}. + */ +public interface RedisClientProvider { + /** + * Provides the redis client for creating pub/sub connections. + * + * @return the redis client. + */ + RedisClient provide(); +} diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..8f82b0a --- /dev/null +++ b/renovate.json @@ -0,0 +1,18 @@ +{ + "extends": [ + "config:base" + ], + "labels": ["dependencies"], + "schedule": [ + "after 9am" + ], + "packageRules": [ + { + "matchUpdateTypes": ["major", "minor", "patch", "pin", "digest", "lockFileMaintenance", "rollback", "bump"], + "automerge": true + } + ], + "ignorePaths": [ + "example" + ] +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..16b9972 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,10 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} + +rootProject.name = "pubsub" + +include("common", "redis", "kotlin-extensions", "kotlin-protobuf") + +project(":kotlin-extensions").projectDir = file("kotlin/extensions") +project(":kotlin-protobuf").projectDir = file("kotlin/protobuf")