diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b9c1c88..bb460bb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -9,7 +9,7 @@ jobs: name: Build runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e568b5d..41eb3a0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,7 +9,7 @@ jobs: name: Release runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: diff --git a/.github/workflows/snapshot-release.yml b/.github/workflows/snapshot-release.yml index 871e261..eb82543 100644 --- a/.github/workflows/snapshot-release.yml +++ b/.github/workflows/snapshot-release.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest if: "github.event.release.prerelease" steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: diff --git a/.github/workflows/snapshot.yml b/.github/workflows/snapshot.yml index 789356b..732fbc6 100644 --- a/.github/workflows/snapshot.yml +++ b/.github/workflows/snapshot.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest if: ${{ !contains(github.event.head_commit.message, 'skip-snapshot') }} steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: diff --git a/README.md b/README.md index 0df819d..bf75d6b 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,8 @@ # agones4j -[![idea](https://www.elegantobjects.org/intellij-idea.svg)](https://www.jetbrains.com/idea/) - ![Sonatype Nexus (Releases)](https://img.shields.io/nexus/r/tr.com.infumia/agones4j?label=maven-central&server=https%3A%2F%2Foss.sonatype.org%2F) ![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/tr.com.infumia/agones4j?label=maven-central&server=https%3A%2F%2Foss.sonatype.org) ## How to Use (Developers) ### Code -```java -final class Server { - - public static void main( - final String[] args - ) { - final var sdk = new tr.com.infumia.agones4j.AgonesSdk(); - } -} -``` ```groovy dependencies { implementation "io.grpc:grpc-stub:1.47.0" @@ -23,3 +11,67 @@ dependencies { implementation "tr.com.infumia:agones4j:VERSION" } ``` +```java +import java.time.Duration; + +void agones() { + final ExecutorService gameServerWatcherExecutor = + Executors.newSingleThreadExecutor(); + final ScheduledExecutorService healthCheckExecutor = + Executors.newSingleThreadScheduledExecutor(); + final Agones agones = Agones.builder() + // Address specification. + // If not specified, localhost:9357 will be used. + // All the following methods are creating a ManagedChannel with 'usePlaintext' + // If you need to use SSL, you can use 'withChannel(ManagedChannel)' method. + .withAddress("localhost", 9357) + .withAddress("localhost") // 9357 + .withAddress(9357) // localhost + .withAddress() // localhost 9357 + .withTarget("localhost:9357") + .withTarget() // localhost:9357 + .withChannel(ManagedChannelBuilder + .forAddress("localhost", 9357) + .usePlaintext() + .build()) + .withChannel() // localhost:9357 + // Game server watcher executor specification. + .withGameServerWatcherExecutor(gameServerWatcherExecutor) + // Health checker executor specification. + // Check you game server's health check threshold and + // set the executor's delay and period accordingly. + .withHealthCheck( + /* delay */Duration.ofSeconds(1L), + /* period */Duration.ofSeconds(2L) + ) + .withHealthCheckerExecutor(healthCheckExecutor) + .build(); + + // Health checking. + // Checks if the executor, delay and period are specified. + if (agones.canHealthCheck()) { + // Automatic health checking. + // Uses the health checker executor and the specified delay and period. + agones.startHealthChecking(); + } + + // Manual health checking. + final StreamObserver requester = agones.healthCheck(); + // onNext needs to be called continuously to keep the game server healthy. + requester.onNext(Empty.getDefaultInstance()); + + // Stopping the health checking. + agones.stopHealthChecking(); + + // Game server watching. + // Checks if the executor is specified. + if (agones.canWatchGameServer()) { + agones.addGameServerWatcher(gameServer -> + // This will be called when the game server is updated. + System.out.println("Game server updated: " + gameServer)); + } + + agones.allocate(); + agones.shutdown(); +} +``` diff --git a/build.gradle.kts b/build.gradle.kts index fd3b315..2d578d0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -15,10 +15,20 @@ val signRequired = !rootProject.property("dev").toString().toBoolean() group = "tr.com.infumia" +repositories { + mavenCentral() +} + +dependencies { + compileOnlyApi(libs.protobuf) + compileOnlyApi(libs.grpc.protobuf) + compileOnlyApi(libs.grpc.stub) + compileOnlyApi(libs.annotationsapi) +} + java { - toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) - } + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 } sourceSets { @@ -33,11 +43,14 @@ sourceSets { } protobuf { + protoc { artifact = libs.protoc.get().toString() } + plugins { id("grpc") { artifact = "io.grpc:protoc-gen-grpc-java:${libs.versions.grpc.get()}" } } + generateProtoTasks { all().forEach { it.plugins { @@ -76,40 +89,12 @@ tasks { } processResources { - duplicatesStrategy = DuplicatesStrategy.INCLUDE + duplicatesStrategy = DuplicatesStrategy.EXCLUDE } - - build { - dependsOn(spotlessApply) - dependsOn(jar) - dependsOn(sourcesJar) - dependsOn(javadocJar) - } -} - -repositories { - mavenCentral() -} - -dependencies { - compileOnlyApi(libs.protobuf) - compileOnlyApi(libs.grpc.protobuf) - compileOnlyApi(libs.grpc.stub) - compileOnlyApi(libs.annotationsapi) - - compileOnly(libs.lombok) - compileOnly(libs.annotations) - - annotationProcessor(libs.lombok) - annotationProcessor(libs.annotations) - - testAnnotationProcessor(libs.lombok) - testAnnotationProcessor(libs.annotations) } spotless { lineEndings = LineEnding.UNIX - isEnforceCheck = false java { target("**/src/main/java/tr/com/infumia/agones4j/**") @@ -120,14 +105,16 @@ spotless { trimTrailingWhitespace() prettier( mapOf( - "prettier" to "2.7.1", - "prettier-plugin-java" to "1.6.2" + "prettier" to "3.2.5", + "prettier-plugin-java" to "2.5.0" ) ).config( mapOf( "parser" to "java", "tabWidth" to 2, - "useTabs" to false + "useTabs" to false, + "printWidth" to 120, + "plugins" to listOf("prettier-plugin-java"), ) ) } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5935a8d..13bc9d0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,10 +1,10 @@ [versions] grpc = "1.61.1" +protobuf = "3.25.2" [libraries] -lombok = { module = "org.projectlombok:lombok", version = "1.18.30" } -annotations = { module = "org.jetbrains:annotations", version = "24.1.0" } -protobuf = { module = "com.google.protobuf:protobuf-java", version = "3.25.2" } +protobuf = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } +protoc = { module = "com.google.protobuf:protoc", version.ref = "protobuf" } grpc-stub = { module = "io.grpc:grpc-stub", version.ref = "grpc" } grpc-protobuf = { module = "io.grpc:grpc-protobuf", version.ref = "grpc" } annotationsapi = { module = "org.apache.tomcat:annotations-api", version = "6.0.53" } diff --git a/gradlew.bat b/gradlew.bat index 93e3f59..25da30d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -43,11 +43,11 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +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 @@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +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 diff --git a/src/main/java/tr/com/infumia/agones4j/Agones.java b/src/main/java/tr/com/infumia/agones4j/Agones.java new file mode 100644 index 0000000..b6ec078 --- /dev/null +++ b/src/main/java/tr/com/infumia/agones4j/Agones.java @@ -0,0 +1,854 @@ +package tr.com.infumia.agones4j; + +import agones.dev.sdk.Sdk; +import agones.dev.sdk.alpha.Alpha; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.stub.StreamObserver; +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Consumer; + +/** + * The interface provides methods to interact with Agones. + */ +public interface Agones extends AutoCloseable { + /** + * Retrieves a new instance of the Agones builder. + * + * @return A new instance of the Agones builder. + */ + static Agones.Builder builder() { + return new AgonesImpl.Builder(); + } + + /** + * Checks if it can watch game server. + *

+ * To enable game server watcher, use {@link Builder#withGameServerWatcherExecutor(ExecutorService)}. + * + * @return {@code true} if it can watch game server, {@code false} otherwise. + */ + boolean canWatchGameServer(); + + /** + * Adds a game server watcher. + *

+ * Game server watchers are called whenever a game server event occurs. + * + * @param watcher A consumer that represents the game server watcher. + * + * @see #canWatchGameServer() + */ + void addGameServerWatcher(Consumer watcher); + + /** + * Checks if it can use health check system of Agones. + *

+ * To enable health check, use {@link Builder#withHealthCheck(Duration, Duration)}. + * + * @return {@code true} if it can use health check system of Agones, {@code false} otherwise. + */ + boolean canHealthCheck(); + + /** + * Starts the health checking. + * + * @throws IllegalStateException if the health check interval not specified. + * @see #canHealthCheck() + */ + void startHealthChecking(); + + /** + * Stops the health checking. + */ + void stopHealthChecking(); + + /** + * Creates a new health check stream. + * + * @param response the response from server. + * + * @return a stream observer to send health check requests. + * + * @see #canHealthCheck() + */ + StreamObserver healthCheckStream(StreamObserver response); + + /** + * Creates a new health check stream. + * + * @return a stream observer to send health check requests. + * + * @see #canHealthCheck() + */ + default StreamObserver healthCheckStream() { + return this.healthCheckStream(Internal.observerEmpty()); + } + + /** + * Call to self Allocation the GameServer. + * + * @param response the response from server. + */ + void allocate(StreamObserver response); + + /** + * Call to self Allocation the GameServer. + */ + default void allocate() { + this.allocate(Internal.observerEmpty()); + } + + /** + * Call to self Allocation the GameServer. + * + * @return A future that represents the result of the allocation operation. + */ + default CompletableFuture allocateFuture() { + return Internal.observerToFuture(this::allocate); + } + + /** + * Retrieves the current {@link Sdk.GameServer} data. + * + * @param response the response from server. + */ + void getGameServer(StreamObserver response); + + /** + * Retrieves the current {@link Sdk.GameServer} data. + * + * @return A future that represents the current game server. + */ + default CompletableFuture getGameServerFuture() { + return Internal.observerToFuture(this::getGameServer); + } + + /** + * Call when the {@link Sdk.GameServer} is ready. + * + * @param response the response from server. + */ + void ready(StreamObserver response); + + /** + * Call when the {@link Sdk.GameServer} is ready. + */ + default void ready() { + this.ready(Internal.observerEmpty()); + } + + /** + * Call when the {@link Sdk.GameServer} is ready. + * + * @return A future that represents the result of the ready operation. + */ + default CompletableFuture readyFuture() { + return Internal.observerToFuture(this::ready); + } + + /** + * Marks the {@link Sdk.GameServer} as the Reserved state for Duration. + * + * @param duration the duration to mark. + * @param response the response from server. + */ + void reserve(Duration duration, StreamObserver response); + + /** + * Marks the {@link Sdk.GameServer} as the Reserved state for Duration. + * + * @param duration the duration to mark. + */ + default void reserve(final Duration duration) { + this.reserve(duration, Internal.observerEmpty()); + } + + /** + * Marks the {@link Sdk.GameServer} as the Reserved state for Duration. + * + * @param duration the duration to mark. + * + * @return A future that represents the result of the reserve operation. + */ + default CompletableFuture reserveFuture(final Duration duration) { + return Internal.observerToFuture(response -> this.reserve(duration, response)); + } + + /** + * Call when the {@link Sdk.GameServer} is shutting down. + * + * @param response the response from server. + */ + void shutdown(StreamObserver response); + + /** + * Call when the {@link Sdk.GameServer} is shutting down. + */ + default void shutdown() { + this.shutdown(Internal.observerEmpty()); + } + + /** + * Call when the {@link Sdk.GameServer} is shutting down. + * + * @return A future that represents the result of the shutdown operation. + */ + default CompletableFuture shutdownFuture() { + return Internal.observerToFuture(this::shutdown); + } + + /** + * Apply an Annotation to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + * @param observer the observer to apply. + */ + void setAnnotation(String key, String value, StreamObserver observer); + + /** + * Apply an Annotation to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + */ + default void setAnnotation(final String key, final String value) { + this.setAnnotation(key, value, Internal.observerEmpty()); + } + + /** + * Apply an Annotation to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + * + * @return A future that represents the result of the set annotation operation. + */ + default CompletableFuture setAnnotationFuture(final String key, final String value) { + return Internal.observerToFuture(response -> this.setAnnotation(key, value, response)); + } + + /** + * Apply a Label to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + * @param response the response from server. + */ + void setLabel(String key, String value, StreamObserver response); + + /** + * Apply a Label to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + */ + default void setLabel(final String key, final String value) { + this.setLabel(key, value, Internal.observerEmpty()); + } + + /** + * Apply a Label to the backing {@link Sdk.GameServer} metadata. + * + * @param key the key to apply. + * @param value the value to apply. + * + * @return A future that represents the result of the set label operation. + */ + default CompletableFuture setLabelFuture(final String key, final String value) { + return Internal.observerToFuture(response -> this.setLabel(key, value, response)); + } + + /** + * Returns the list of the currently connected player ids. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the + * {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use + * {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @param response the response from server. + */ + void getConnectedPlayersFuture(StreamObserver> response); + + /** + * Returns the list of the currently connected player ids. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the + * {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use + * {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @return A future that represents the list of the currently connected player ids. + */ + default CompletableFuture> getConnectedPlayersFuture() { + return Internal.observerToFuture(this::getConnectedPlayersFuture); + } + + /** + * Increases the SDK’s stored player count by one, and appends this playerID to {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. + *

+ * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} are then set to update the player count and id list a second from now, unless there is already an update pending, in which case the update joins that batch operation. + *

+ * The response returns true and adds the playerID to the list of playerIDs if this playerID was not already in the list of connected playerIDs. + *

+ * If the playerID exists within the list of connected playerIDs, will return false, and the list of connected playerIDs will be left unchanged. + *

+ * An error will be returned if the playerID was not already in the list of connected playerIDs but the player capacity for the server has been reached. + * The playerID will not be added to the list of playerIDs. + *

+ * WARNING: Do not use this method if you are manually managing {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} through the Kubernetes API, as indeterminate results will occur. + * + * @param playerId the player id to connect. + * @param response the response from server. + */ + void playerConnect(String playerId, StreamObserver response); + + /** + * Increases the SDK’s stored player count by one, and appends this playerID to {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. + * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} are then set to update the player count and id list a second from now, unless there is already an update pending, in which case the update joins that batch operation. + *

+ * If the playerID exists within the list of connected playerIDs, will return false, and the list of connected playerIDs will be left unchanged. + *

+ * An error will be returned if the playerID was not already in the list of connected playerIDs but the player capacity for the server has been reached. + * The playerID will not be added to the list of playerIDs. + *

+ * WARNING: Do not use this method if you are manually managing {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} through the Kubernetes API, as indeterminate results will occur. + * + * @param playerId the player id to connect. + * + * @return A future that represents the result of the player connect operation. + */ + default CompletableFuture playerConnectFuture(final String playerId) { + return Internal.observerToFuture(response -> this.playerConnect(playerId, response)); + } + + /** + * Decreases the SDK’s stored player count by one, and removes the playerID from {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} + * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} are then set to update the player count and id list a second from now, unless there is already an update pending, in which case the update joins that batch operation. + *

+ * The response returns true and removes the playerID from the list of connected playerIDs if the playerID value exists within the list. + *

+ * If the playerID was not in the list of connected playerIDs, the call will return false, and the connected playerID list will be left unchanged. + *

+ * WARNING: Do not use this method if you are manually managing {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} through the Kubernetes API, as indeterminate results will occur. + * + * @param playerId the player id to disconnect. + * @param response the response from server. + */ + void playerDisconnect(String playerId, StreamObserver response); + + /** + * Decreases the SDK’s stored player count by one, and removes the playerID from {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} + * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} are then set to update the player count and id list a second from now, unless there is already an update pending, in which case the update joins that batch operation. + *

+ * If the playerID was not in the list of connected playerIDs, the call will return false, and the connected playerID list will be left unchanged. + *

+ * WARNING: Do not use this method if you are manually managing {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} through the Kubernetes API, as indeterminate results will occur. + * + * @param playerId the player id to disconnect. + * + * @return A future that represents the result of the player disconnect operation. + */ + default CompletableFuture playerDisconnectFuture(final String playerId) { + return Internal.observerToFuture(response -> this.playerDisconnect(playerId, response)); + } + + /** + * Returns if the playerID is currently connected to the {@link Sdk.GameServer}. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to determine connected status. + * + * @param playerId the player id to return. + * @param response the response from server. + */ + void isPlayerConnected(String playerId, StreamObserver response); + + /** + * Returns if the playerID is currently connected to the {@link Sdk.GameServer}. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to determine connected status. + * + * @param playerId the player id to return. + * + * @return A future that represents the result of the is player connected operation. + */ + default CompletableFuture isPlayerConnected(final String playerId) { + return Internal.observerToFuture(response -> this.isPlayerConnected(playerId, response)); + } + + /** + * Update the {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} value with a new capacity. + * + * @param capacity the capacity to update. + * @param response the response from server. + */ + void setPlayerCapacity(long capacity, StreamObserver response); + + /** + * Update the {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} value with a new capacity. + * + * @param capacity the capacity to update. + * + * @return A future that represents the result of the set player capacity operation. + */ + default CompletableFuture setPlayerCapacityFuture(final long capacity) { + return Internal.observerToFuture(response -> this.setPlayerCapacity(capacity, response)); + } + + /** + * Retrieves the current player capacity. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @param response the response from server. + */ + void getPlayerCapacity(StreamObserver response); + + /** + * Retrieves the current player capacity. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @return A future that represents the current player capacity. + */ + default CompletableFuture getPlayerCapacityFuture() { + return Internal.observerToFuture(this::getPlayerCapacity); + } + + /** + * Retrieves the current player count. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getCount()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @param response the response from server. + */ + void getPlayerCount(StreamObserver response); + + /** + * Retrieves the current player count. + *

+ * This is always accurate from what has been set through this SDK, even if the value has yet to be updated on the {@link Sdk.GameServer} status resource. + *

+ * If {@link Sdk.GameServer.Status.PlayerStatus#getCount()} is set manually through the Kubernetes API, use {@link Agones#getGameServerFuture()} or {@link Agones#addGameServerWatcher(Consumer)} instead to view this value. + * + * @return A future that represents the current player count. + */ + default CompletableFuture getPlayerCountFuture() { + return Internal.observerToFuture(this::getPlayerCount); + } + + /** + * gets a list. + *

+ * returns NOT_FOUND if the List does not exist. + * + * @param name the name to get. + * @param response the response from server. + */ + void getList(String name, StreamObserver response); + + /** + * gets a list. + *

+ * Returns NOT_FOUND if the List does not exist. + * + * @param name the name to get. + * + * @return the list. + */ + default CompletableFuture getList(final String name) { + return Internal.observerToFuture(response -> this.getList(name, response)); + } + + /** + * Adds a value to a list and returns updated list. + *

+ * Returns NOT_FOUND if the list does not exist. + *

+ * Returns ALREADY_EXISTS if the value is already in the list. + *

+ * Returns OUT_OF_RANGE if the list is already at Capacity. + * + * @param name the name to add. + * @param value the value to add. + * @param response the response from server. + */ + void addList(String name, String value, StreamObserver response); + + /** + * Adds a value to a list and returns updated list. + *

+ * Returns NOT_FOUND if the list does not exist. + *

+ * Returns ALREADY_EXISTS if the value is already in the list. + *

+ * Returns OUT_OF_RANGE if the list is already at Capacity. + * + * @param name the name to add. + * @param value the value to add. + * + * @return the updated list. + */ + default CompletableFuture addListFuture(final String name, final String value) { + return Internal.observerToFuture(response -> this.addList(name, value, response)); + } + + /** + * Removes a value from a list and returns updated list. + *

+ * Returns NOT_FOUND if the list does not exist. + *

+ * Returns NOT_FOUND if the value is not in the list. + * + * @param name the name to remove. + * @param value the value to remove. + * @param response the response from server. + */ + void removeList(String name, String value, StreamObserver response); + + /** + * Removes a value from a list and returns updated list. + *

+ * Returns NOT_FOUND if the list does not exist. + *

+ * Returns NOT_FOUND if the value is not in the list. + * + * @param name the name to remove. + * @param value the value to remove. + * + * @return the updated list. + */ + default CompletableFuture removeListFuture(final String name, final String value) { + return Internal.observerToFuture(response -> this.removeList(name, value, response)); + } + + /** + * Returns the updated list. + *

+ * Returns NOT_FOUND if the list does not exist (name cannot be updated). + *

+ * THIS WILL OVERWRITE ALL EXISTING LIST.VALUES WITH ANY REQUEST LIST.VALUES. + *

+ * Use {@link #addListFuture(String, String)} or {@link #removeListFuture(String, String)} for modifying the + * List.Values field. + *

+ * Returns INVALID_ARGUMENT if the field mask path(s) are not field(s) of the list. + * + * @param list the list to update. + * @param updateMask the update mask to update. + * @param response the response from server. + */ + void updateList(AgonesList list, List updateMask, StreamObserver response); + + /** + * Returns the updated list. + *

+ * Returns NOT_FOUND if the list does not exist (name cannot be updated). + *

+ * THIS WILL OVERWRITE ALL EXISTING LIST.VALUES WITH ANY REQUEST LIST.VALUES. + *

+ * Use {@link #addListFuture(String, String)} or {@link #removeListFuture(String, String)} for modifying the + * List.Values field. + *

+ * Returns INVALID_ARGUMENT if the field mask path(s) are not field(s) of the list. + * + * @param list the list to update. + * @param updateMask the update mask to update. + * + * @return the updated list. + */ + default CompletableFuture updateList(final AgonesList list, final List updateMask) { + return Internal.observerToFuture(response -> this.updateList(list, updateMask, response)); + } + + /** + * gets a counter. + *

+ * Returns NOT_FOUND if the counter does not exist. + * + * @param name the name of the counter. + * @param response the response from server. + */ + void getCounter(String name, StreamObserver response); + + /** + * gets a counter. + *

+ * Returns NOT_FOUND if the counter does not exist. + * + * @param name the name of the counter. + * + * @return the counter. + */ + default CompletableFuture getCounterFuture(final String name) { + return Internal.observerToFuture(response -> this.getCounter(name, response)); + } + + /** + * Increases the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to increase. + * @param response the response from server. + */ + void increaseCounter(String name, long amount, StreamObserver response); + + /** + * Increases the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to increase. + * + * @return the counter. + */ + default CompletableFuture increaseCounterFuture(final String name, final long amount) { + return Internal.observerToFuture(response -> this.increaseCounter(name, amount, response)); + } + + /** + * Decreases the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to decrease. + * @param response the response from server. + */ + void decreaseCounter(String name, long amount, StreamObserver response); + + /** + * Decreases the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to decrease. + * + * @return the counter. + */ + default CompletableFuture decreaseCounter(final String name, final long amount) { + return Internal.observerToFuture(response -> this.decreaseCounter(name, amount, response)); + } + + /** + * Sets the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to set. + * @param response the response from server. + */ + void setCounterCount(String name, long amount, StreamObserver response); + + /** + * Sets the count of the Counter by the specified amount. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + *

+ * Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. + * + * @param name the name of the counter. + * @param amount the amount to set. + * + * @return the counter. + */ + default CompletableFuture setCounterCountFuture(String name, long amount) { + return Internal.observerToFuture(response -> this.setCounterCount(name, amount, response)); + } + + /** + * Sets the capacity of the Counter by the specified amount. + *

+ * 0 is no limit. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + * + * @param name the name of the counter. + * @param amount the amount to set. + * @param response the response from server. + */ + void setCounterCapacity(String name, long amount, StreamObserver response); + + /** + * Sets the capacity of the Counter by the specified amount. + *

+ * 0 is no limit. + *

+ * Returns NOT_FOUND if the Counter does not exist (name cannot be updated). + * + * @param name the name of the counter. + * @param amount the amount to set. + * + * @return the counter. + */ + default CompletableFuture setCounterCapacityFuture(final String name, final long amount) { + return Internal.observerToFuture(response -> this.setCounterCapacity(name, amount, response)); + } + + /** + * A builder for creating instances of Agones with specified configurations. + */ + interface Builder { + /** + * Builds an instance of Agones using the specified configuration. + * + * @return An instance of Agones. + */ + Agones build(); + + /** + * Sets the address for the Agones Builder. + * + * @param host The host address to be set. + * @param port The port number to be set. + * + * @return The Agones Builder instance. + * + * @see ManagedChannelBuilder#forAddress(String, int) + * @see ManagedChannelBuilder#usePlaintext() + */ + default Builder withAddress(final String host, final int port) { + return this.withChannel(ManagedChannelBuilder.forAddress(host, port).usePlaintext().build()); + } + + /** + * Sets the address for the Agones Builder. + * + * @param host The host address to be set. + * + * @return The Agones Builder instance. + */ + default Builder withAddress(final String host) { + return this.withAddress(host, Internal.GRPC_PORT); + } + + /** + * Sets the address for the Agones Builder. + * + * @param port The port number to be set. + * + * @return The Agones Builder instance. + */ + default Builder withAddress(final int port) { + return this.withAddress(Internal.GRPC_HOST, port); + } + + /** + * Sets the address for the Agones Builder. + * + * @return The Agones Builder instance. + */ + default Builder withAddress() { + return this.withAddress(Internal.GRPC_HOST); + } + + /** + * Sets the target for the Agones Builder. + * + * @param target The target to be set. + * + * @return The Agones Builder instance. + * + * @see ManagedChannelBuilder#forTarget(String) + * @see ManagedChannelBuilder#usePlaintext() + */ + default Builder withTarget(final String target) { + return this.withChannel(ManagedChannelBuilder.forTarget(target).usePlaintext().build()); + } + + /** + * Sets the target for the Agones Builder. + * + * @return The Agones Builder instance. + */ + default Builder withTarget() { + Objects.requireNonNull(Internal.GRPC_ADDRESS, "Environment variable 'AGONES_SDK_GRPC_ADDRESS' is not set!"); + return this.withTarget(Internal.GRPC_ADDRESS); + } + + /** + * Sets the channel from environment variables for the Agones Builder. + * + * @return The Agones Builder instance. + */ + default Builder withChannel() { + if (Internal.GRPC_ADDRESS == null) { + return this.withAddress(); + } else { + return this.withTarget(); + } + } + + /** + * Sets the ManagedChannel for the Agones Builder. + * + * @param channel The ManagedChannel to be set. + * + * @return The Agones Builder instance. + */ + Builder withChannel(ManagedChannel channel); + + /** + * Sets the executor for the game server watcher. + * + * @param executor The executor service to be used by the game server watcher. {@code null} to disable it. Disabled by default. + * + * @return The Agones Builder instance. + */ + Builder withGameServerWatcherExecutor(ExecutorService executor); + + /** + * Sets the health check interval for the Agones Builder. + * + * @param delay The delay duration for health checks. {@code null} to disable it. Disabled by default. + * @param period The interval duration for health checks. + * + * @return The Agones Builder instance. + */ + Builder withHealthCheck(Duration delay, Duration period); + + /** + * Sets the health check executor for the builder. + * + * @param executor the scheduled executor service to be used for health checks. {@code null} to disable it. Default is {@link Executors#newSingleThreadScheduledExecutor()} + * + * @return The Agones Builder instance. + */ + Builder withHealthCheckExecutor(ScheduledExecutorService executor); + } +} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesAlphaSdk.java b/src/main/java/tr/com/infumia/agones4j/AgonesAlphaSdk.java deleted file mode 100644 index 0beabc6..0000000 --- a/src/main/java/tr/com/infumia/agones4j/AgonesAlphaSdk.java +++ /dev/null @@ -1,369 +0,0 @@ -package tr.com.infumia.agones4j; - -import agones.dev.sdk.Sdk; -import agones.dev.sdk.alpha.Alpha; -import agones.dev.sdk.alpha.SDKGrpc; -import com.google.protobuf.FieldMask; -import io.grpc.ManagedChannel; -import io.grpc.stub.StreamObserver; -import lombok.AccessLevel; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.NotNull; - -/** - * a class that represents Agones Sdk. - */ -@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) -public final class AgonesAlphaSdk { - - /** - * the stub. - */ - @NotNull - SDKGrpc.SDKStub stub; - - /** - * ctor. - * - * @param channel the channel. - */ - AgonesAlphaSdk(@NotNull final ManagedChannel channel) { - this.stub = SDKGrpc.newStub(channel); - } - - /** - * adds a value to a list and returns updated list. returns NOT_FOUND if the list does not exist. returns - * ALREADY_EXISTS if the value is already in the list. returns OUT_OF_RANGE if the list is already at Capacity. - * - * @param name the name to add. - * @param value the value to add. - * @param observer the observer to add. - */ - public void addList( - @NotNull final String name, - @NotNull final String value, - @NotNull final StreamObserver observer - ) { - this.stub.addListValue( - Alpha.AddListValueRequest - .newBuilder() - .setName(name) - .setValue(value) - .build(), - observer - ); - } - - /** - * returns the list of the currently connected player ids. - * this is always accurate from what has been set through this SDK, even if the value has yet to be updated on the - * {@link Sdk.GameServer} status resource. - * if {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use - * {@link AgonesSdk#getGameServer(StreamObserver)} or {@link AgonesSdk#watchGameServer(StreamObserver)} instead to - * view this value. - * - * @param observer the observer to return. - */ - public void getConnectedPlayers( - @NotNull final StreamObserver observer - ) { - this.stub.getConnectedPlayers(Alpha.Empty.getDefaultInstance(), observer); - } - - /** - * gets a counter. returns NOT_FOUND if the counter does not exist. - * - * @param name the name of the counter. - * @param observer the observer to get counter. - */ - public void getCounter( - @NotNull final String name, - @NotNull final StreamObserver observer - ) { - this.stub.getCounter( - Alpha.GetCounterRequest.newBuilder().setName(name).build(), - observer - ); - } - - /** - * gets a list. returns NOT_FOUND if the List does not exist. - * - * @param name the name to get. - * @param observer the observer to get. - */ - public void getList( - @NotNull final String name, - @NotNull final StreamObserver observer - ) { - this.stub.getList( - Alpha.GetListRequest.newBuilder().setName(name).build(), - observer - ); - } - - /** - * retrieves the current player capacity. - * this is always accurate from what has been set through this SDK, even if the value has yet to be updated on the - * {@link Sdk.GameServer} status resource. - * if {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} is set manually through the Kubernetes API, use - * {@link AgonesSdk#getGameServer(StreamObserver)} or {@link AgonesSdk#watchGameServer(StreamObserver)} instead to - * view this value. - * - * @param observer the observer to retrieve. - */ - public void getPlayerCapacity( - @NotNull final StreamObserver observer - ) { - this.stub.getPlayerCapacity(Alpha.Empty.getDefaultInstance(), observer); - } - - /** - * retrieves the current player count. - * this is always accurate from what has been set through this SDK, even if the value has yet to be updated on the - * {@link Sdk.GameServer} status resource. - * if {@link Sdk.GameServer.Status.PlayerStatus#getCount()} is set manually through the Kubernetes API, use - * {@link AgonesSdk#getGameServer(StreamObserver)} or {@link AgonesSdk#watchGameServer(StreamObserver)} instead to - * view this value. - * - * @param observer the observer to retrieve. - */ - public void getPlayerCount( - @NotNull final StreamObserver observer - ) { - this.stub.getPlayerCount(Alpha.Empty.getDefaultInstance(), observer); - } - - /** - * returns if the playerID is currently connected to the {@link Sdk.GameServer}. - * this is always accurate from what has been set through this SDK, even if the value has yet to be updated on the - * {@link Sdk.GameServer} status resource. - * if {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use - * {@link AgonesSdk#getGameServer(StreamObserver)} or {@link AgonesSdk#watchGameServer(StreamObserver)} instead to - * determine connected status. - * - * @param playerId the player id to return. - * @param observer the observer to return. - */ - public void isPlayerConnected( - @NotNull final Alpha.PlayerID playerId, - @NotNull final StreamObserver observer - ) { - this.stub.isPlayerConnected(playerId, observer); - } - - /** - * returns if the playerID is currently connected to the {@link Sdk.GameServer}. - * this is always accurate from what has been set through this SDK, even if the value has yet to be updated on the - * {@link Sdk.GameServer} status resource. - * if {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} is set manually through the Kubernetes API, use - * {@link AgonesSdk#getGameServer(StreamObserver)} or {@link AgonesSdk#watchGameServer(StreamObserver)} instead to - * determine connected status. - * - * @param playerId the player id to return. - * @param observer the observer to return. - */ - public void isPlayerConnected( - @NotNull final String playerId, - @NotNull final StreamObserver observer - ) { - this.isPlayerConnected( - Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), - observer - ); - } - - /** - * increases the SDK’s stored player count by one, and appends this playerID to - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. - * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} - * are then set to update the player count and id list a second from now, unless there is already an update pending, - * in which case the update joins that batch operation. - * returns true and adds the playerID to the list of playerIDs if this playerID was not already in the list of - * connected playerIDs. - * if the playerID exists within the list of connected playerIDs, will return false, and the list of connected - * playerIDs will be left unchanged. - * an error will be returned if the playerID was not already in the list of connected playerIDs but the player - * capacity for the server has been reached. - * the playerID will not be added to the list of playerIDs. - * warning: do not use this method if you are manually managing - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} - * through the Kubernetes API, as indeterminate results will occur. - * - * @param playerId the player id to connect. - * @param observer the observer to connect. - */ - public void playerConnect( - @NotNull final Alpha.PlayerID playerId, - @NotNull final StreamObserver observer - ) { - this.stub.playerConnect(playerId, observer); - } - - /** - * increases the SDK’s stored player count by one, and appends this playerID to - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. - * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} - * are then set to update the player count and id list a second from now, unless there is already an update pending, - * in which case the update joins that batch operation. - * returns true and adds the playerID to the list of playerIDs if this playerID was not already in the list of - * connected playerIDs. - * if the playerID exists within the list of connected playerIDs, will return false, and the list of connected - * playerIDs will be left unchanged. - * an error will be returned if the playerID was not already in the list of connected playerIDs but the player - * capacity for the server has been reached. - * the playerID will not be added to the list of playerIDs. - * warning: do not use this method if you are manually managing - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} - * through the Kubernetes API, as indeterminate results will occur. - * - * @param playerId the player id to connect. - * @param observer the observer to connect. - */ - public void playerConnect( - @NotNull final String playerId, - @NotNull final StreamObserver observer - ) { - this.playerConnect( - Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), - observer - ); - } - - /** - * decreases the SDK’s stored player count by one, and removes the playerID from - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. - * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} - * are then set to update the player count and id list a second from now, unless there is already an update pending, - * in which case the update joins that batch operation. - * will return true and remove the supplied playerID from the list of connected playerIDs if the playerID value exists - * within the list. - * if the playerID was not in the list of connected playerIDs, the call will return false, and the connected playerID - * list will be left unchanged. - * warning: do not use this method if you are manually managing - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} - * through the Kubernetes API, as indeterminate results will occur. - * - * @param playerId the player id to disconnect. - * @param observer the observer to disconnect. - */ - public void playerDisconnect( - @NotNull final Alpha.PlayerID playerId, - @NotNull final StreamObserver observer - ) { - this.stub.playerDisconnect(playerId, observer); - } - - /** - * decreases the SDK’s stored player count by one, and removes the playerID from - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()}. - * {@link Sdk.GameServer.Status.PlayerStatus#getCount()} and {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} - * are then set to update the player count and id list a second from now, unless there is already an update pending, - * in which case the update joins that batch operation. - * will return true and remove the supplied playerID from the list of connected playerIDs if the playerID value exists - * within the list. - * if the playerID was not in the list of connected playerIDs, the call will return false, and the connected playerID - * list will be left unchanged. - * warning: do not use this method if you are manually managing - * {@link Sdk.GameServer.Status.PlayerStatus#getIdsList()} and {@link Sdk.GameServer.Status.PlayerStatus#getCount()} - * through the Kubernetes API, as indeterminate results will occur. - * - * @param playerId the player id to disconnect. - * @param observer the observer to disconnect. - */ - public void playerDisconnect( - @NotNull final String playerId, - @NotNull final StreamObserver observer - ) { - this.playerDisconnect( - Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), - observer - ); - } - - /** - * removes a value from a list and returns updated list. returns NOT_FOUND if the list does not exist. returns - * NOT_FOUND if the value is not in the list. - * - * @param name the name to remove. - * @param value the value to remove. - * @param observer the observer to add. - */ - public void removeList( - @NotNull final String name, - @NotNull final String value, - @NotNull final StreamObserver observer - ) { - this.stub.removeListValue( - Alpha.RemoveListValueRequest - .newBuilder() - .setName(name) - .setValue(value) - .build(), - observer - ); - } - - /** - * update the {@link Sdk.GameServer.Status.PlayerStatus#getCapacity()} value with a new capacity. - * - * @param capacity the capacity to update. - * @param observer the observer to update. - */ - public void setPlayerCapacity( - @NotNull final Alpha.Count capacity, - @NotNull final StreamObserver observer - ) { - this.stub.setPlayerCapacity(capacity, observer); - } - - /** - * returns the updated counter. returns NOT_FOUND if the counter does not exist (name cannot be updated). returns - * OUT_OF_RANGE if the count is out of range [0,Capacity]. returns INVALID_ARGUMENT if the field mask path(s) are not - * field(s) of the counter. if a field mask path(s) is specified, but the value is not set in the request counter - * object, then the default value for the variable will be set (i.e. 0 for "capacity" or "count"). - * - * @param counter the counter to update. - * @param updateMask the update mask to update. - * @param observer the observer to update. - */ - public void updateCounter( - @NotNull final Alpha.Counter counter, - @NotNull final FieldMask updateMask, - @NotNull final StreamObserver observer - ) { - this.stub.updateCounter( - Alpha.UpdateCounterRequest - .newBuilder() - .setCounter(counter) - .setUpdateMask(updateMask) - .build(), - observer - ); - } - - /** - * returns the updated list. returns NOT_FOUND if the list does not exist (name cannot be updated). - *

- * **THIS WILL OVERWRITE ALL EXISTING LIST.VALUES WITH ANY REQUEST LIST.VALUES** - *

- * use addListValue() or removeListValue() for modifying the List.Values field. - * returns INVALID_ARGUMENT if the field mask path(s) are not field(s) of the list. - * - * @param observer the observer to update. - */ - public void updateList( - @NotNull final Alpha.List list, - @NotNull final FieldMask updateMask, - @NotNull final StreamObserver observer - ) { - this.stub.updateList( - Alpha.UpdateListRequest - .newBuilder() - .setList(list) - .setUpdateMask(updateMask) - .build(), - observer - ); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesBetaSdk.java b/src/main/java/tr/com/infumia/agones4j/AgonesBetaSdk.java deleted file mode 100644 index c24d10f..0000000 --- a/src/main/java/tr/com/infumia/agones4j/AgonesBetaSdk.java +++ /dev/null @@ -1,29 +0,0 @@ -package tr.com.infumia.agones4j; - -import agones.dev.sdk.beta.SDKGrpc; -import io.grpc.ManagedChannel; -import lombok.AccessLevel; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.NotNull; - -/** - * a class that represents Agones Sdk. - */ -@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) -public final class AgonesBetaSdk { - - /** - * the stub. - */ - @NotNull - SDKGrpc.SDKStub stub; - - /** - * ctor. - * - * @param channel the channel. - */ - AgonesBetaSdk(@NotNull final ManagedChannel channel) { - this.stub = SDKGrpc.newStub(channel); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesCounter.java b/src/main/java/tr/com/infumia/agones4j/AgonesCounter.java new file mode 100644 index 0000000..275af7f --- /dev/null +++ b/src/main/java/tr/com/infumia/agones4j/AgonesCounter.java @@ -0,0 +1,77 @@ +package tr.com.infumia.agones4j; + +import java.util.Objects; +import java.util.StringJoiner; + +/** + * Represents a counter in the Agones system. + */ +public final class AgonesCounter { + + private final String name; + private final long capacity; + private final long count; + + AgonesCounter(final String name, final long capacity, final long count) { + this.name = name; + this.capacity = capacity; + this.count = count; + } + + /** + * Retrieves the counter name. + * + * @return the name. + */ + public String getName() { + return this.name; + } + + /** + * Retrieves the counter capacity. + * + * @return the capacity. + */ + public long getCapacity() { + return this.capacity; + } + + /** + * Returns the counter count. + * + * @return the count. + */ + public long getCount() { + return this.count; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null || this.getClass() != obj.getClass()) { + return false; + } + final AgonesCounter that = (AgonesCounter) obj; + return ( + Objects.equals(this.capacity, that.capacity) && + Objects.equals(this.name, that.name) && + Objects.equals(this.count, that.count) + ); + } + + @Override + public int hashCode() { + return Objects.hash(this.name, this.capacity, this.count); + } + + @Override + public String toString() { + return new StringJoiner(", ", AgonesCounter.class.getSimpleName() + "[", "]") + .add("name='" + this.name + "'") + .add("capacity=" + this.capacity) + .add("count=" + this.count) + .toString(); + } +} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesImpl.java b/src/main/java/tr/com/infumia/agones4j/AgonesImpl.java new file mode 100644 index 0000000..d6414df --- /dev/null +++ b/src/main/java/tr/com/infumia/agones4j/AgonesImpl.java @@ -0,0 +1,382 @@ +package tr.com.infumia.agones4j; + +import agones.dev.sdk.Sdk; +import agones.dev.sdk.alpha.Alpha; +import com.google.protobuf.FieldMask; +import com.google.protobuf.Int64Value; +import io.grpc.ManagedChannel; +import io.grpc.stub.StreamObserver; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +final class AgonesImpl implements Agones { + + private final ManagedChannel channel; + + private final agones.dev.sdk.SDKGrpc.SDKStub sdk; + private final agones.dev.sdk.beta.SDKGrpc.SDKStub beta; + private final agones.dev.sdk.alpha.SDKGrpc.SDKStub alpha; + + private final ExecutorService gameServerWatcherExecutor; + private List> gameServerWatchers; + + private final Duration healthCheckDelay; + private final ScheduledExecutorService healthCheckExecutor; + private final Duration healthCheckPeriod; + private ScheduledFuture healthCheckTask; + + private AgonesImpl(final Builder builder) { + this.channel = builder.channel; + this.gameServerWatcherExecutor = builder.gameServerWatcherExecutor; + this.healthCheckExecutor = builder.healthCheckExecutor(); + this.healthCheckDelay = builder.healthCheckDelay; + this.healthCheckPeriod = builder.healthCheckPeriod; + this.sdk = agones.dev.sdk.SDKGrpc.newStub(builder.channel); + this.beta = agones.dev.sdk.beta.SDKGrpc.newStub(builder.channel); + this.alpha = agones.dev.sdk.alpha.SDKGrpc.newStub(builder.channel); + } + + @Override + public boolean canWatchGameServer() { + return this.gameServerWatcherExecutor != null; + } + + @Override + public void addGameServerWatcher(final Consumer watcher) { + Objects.requireNonNull(this.gameServerWatcherExecutor, "Game server watcher is not enabled!"); + if (this.gameServerWatchers == null) { + this.gameServerWatchers = Collections.synchronizedList(new ArrayList<>()); + final StreamObserver response = Internal.observerOnNext( + this.gameServerWatcherExecutor, + this.gameServerWatchers + ); + this.sdk.watchGameServer(Sdk.Empty.getDefaultInstance(), response); + } + this.gameServerWatchers.add(watcher); + } + + @Override + public boolean canHealthCheck() { + return this.healthCheckExecutor != null && this.healthCheckDelay != null && this.healthCheckPeriod != null; + } + + @Override + public void startHealthChecking() { + if (this.healthCheckExecutor == null || this.healthCheckDelay == null || this.healthCheckPeriod == null) { + throw new IllegalStateException("Health check is not enabled!"); + } + if (this.healthCheckTask != null) { + this.healthCheckTask.cancel(true); + } + final StreamObserver request = this.healthCheckStream(Internal.observerEmpty()); + this.healthCheckTask = + this.healthCheckExecutor.scheduleAtFixedRate( + () -> { + if (this.healthCheckTask != null && !this.healthCheckTask.isDone()) { + request.onNext(Sdk.Empty.getDefaultInstance()); + } + }, + this.healthCheckDelay.toMillis(), + this.healthCheckPeriod.toMillis(), + TimeUnit.MILLISECONDS + ); + } + + @Override + public void stopHealthChecking() { + if (this.healthCheckTask != null) { + this.healthCheckTask.cancel(true); + this.healthCheckTask = null; + } + } + + @Override + public StreamObserver healthCheckStream(final StreamObserver response) { + return this.sdk.health(response); + } + + @Override + public void allocate(final StreamObserver response) { + this.sdk.allocate(Sdk.Empty.getDefaultInstance(), response); + } + + @Override + public void getGameServer(final StreamObserver response) { + this.sdk.getGameServer(Sdk.Empty.getDefaultInstance(), response); + } + + @Override + public void ready(final StreamObserver response) { + this.sdk.ready(Sdk.Empty.getDefaultInstance(), response); + } + + @Override + public void reserve(final Duration duration, final StreamObserver response) { + this.sdk.reserve(Sdk.Duration.newBuilder().setSeconds(duration.getSeconds()).build(), response); + } + + @Override + public void shutdown(final StreamObserver response) { + this.sdk.shutdown(Sdk.Empty.getDefaultInstance(), response); + } + + @Override + public void setAnnotation(final String key, final String value, final StreamObserver observer) { + this.sdk.setAnnotation(Sdk.KeyValue.newBuilder().setKey(key).setValue(value).build(), observer); + } + + @Override + public void setLabel(final String key, final String value, final StreamObserver response) { + this.sdk.setLabel(Sdk.KeyValue.newBuilder().setKey(key).setValue(value).build(), response); + } + + @Override + public void getConnectedPlayersFuture(final StreamObserver> response) { + this.alpha.getConnectedPlayers( + Alpha.Empty.getDefaultInstance(), + Internal.observerMap(response, Alpha.PlayerIDList::getListList) + ); + } + + @Override + public void playerConnect(final String playerId, final StreamObserver response) { + this.alpha.playerConnect( + Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), + Internal.observerMap(response, Alpha.Bool::getBool) + ); + } + + @Override + public void playerDisconnect(final String playerId, final StreamObserver response) { + this.alpha.playerDisconnect( + Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), + Internal.observerMap(response, Alpha.Bool::getBool) + ); + } + + @Override + public void isPlayerConnected(final String playerId, final StreamObserver response) { + this.alpha.isPlayerConnected( + Alpha.PlayerID.newBuilder().setPlayerID(playerId).build(), + Internal.observerMap(response, Alpha.Bool::getBool) + ); + } + + @Override + public void setPlayerCapacity(final long capacity, final StreamObserver response) { + this.alpha.setPlayerCapacity(Alpha.Count.newBuilder().setCount(capacity).build(), Internal.observerEmptyAlpha()); + } + + @Override + public void getPlayerCapacity(final StreamObserver response) { + this.alpha.getPlayerCapacity( + Alpha.Empty.getDefaultInstance(), + Internal.observerMap(response, Alpha.Count::getCount) + ); + } + + @Override + public void getPlayerCount(final StreamObserver response) { + this.alpha.getPlayerCount(Alpha.Empty.getDefaultInstance(), Internal.observerMap(response, Alpha.Count::getCount)); + } + + @Override + public void getList(final String name, final StreamObserver response) { + final Alpha.GetListRequest request = Alpha.GetListRequest.newBuilder().setName(name).build(); + this.alpha.getList(request, Internal.observerMap(response, Internal::toList)); + } + + @Override + public void addList(final String name, final String value, final StreamObserver response) { + final Alpha.AddListValueRequest request = Alpha.AddListValueRequest + .newBuilder() + .setName(name) + .setValue(value) + .build(); + this.alpha.addListValue(request, Internal.observerMap(response, Internal::toList)); + } + + @Override + public void removeList(final String name, final String value, final StreamObserver response) { + final Alpha.RemoveListValueRequest request = Alpha.RemoveListValueRequest + .newBuilder() + .setName(name) + .setValue(value) + .build(); + this.alpha.removeListValue(request, Internal.observerMap(response, Internal::toList)); + } + + @Override + public void updateList( + final AgonesList list, + final List updateMask, + final StreamObserver response + ) { + final FieldMask mask = FieldMask.newBuilder().addAllPaths(updateMask).build(); + final Alpha.UpdateListRequest request = Alpha.UpdateListRequest + .newBuilder() + .setList(Internal.toAgonesList(list)) + .setUpdateMask(mask) + .build(); + this.alpha.updateList(request, Internal.observerMap(response, Internal::toList)); + } + + @Override + public void getCounter(final String name, final StreamObserver response) { + final Alpha.GetCounterRequest request = Alpha.GetCounterRequest.newBuilder().setName(name).build(); + this.alpha.getCounter(request, Internal.observerMap(response, Internal::toCounter)); + } + + @Override + public void increaseCounter(final String name, final long amount, final StreamObserver response) { + final Alpha.CounterUpdateRequest update = Alpha.CounterUpdateRequest + .newBuilder() + .setName(name) + .setCountDiff(amount >= 0 ? amount : Math.abs(amount)) + .build(); + final Alpha.UpdateCounterRequest request = Alpha.UpdateCounterRequest + .newBuilder() + .setCounterUpdateRequest(update) + .build(); + this.alpha.updateCounter(request, Internal.observerMap(response, Internal::toCounter)); + } + + @Override + public void decreaseCounter(final String name, final long amount, final StreamObserver response) { + final Alpha.CounterUpdateRequest update = Alpha.CounterUpdateRequest + .newBuilder() + .setName(name) + .setCountDiff(amount >= 0 ? -amount : amount) + .build(); + final Alpha.UpdateCounterRequest request = Alpha.UpdateCounterRequest + .newBuilder() + .setCounterUpdateRequest(update) + .build(); + this.alpha.updateCounter(request, Internal.observerMap(response, Internal::toCounter)); + } + + @Override + public void setCounterCount(final String name, final long amount, final StreamObserver response) { + final Alpha.CounterUpdateRequest update = Alpha.CounterUpdateRequest + .newBuilder() + .setName(name) + .setCount(Int64Value.newBuilder().setValue(amount).build()) + .build(); + final Alpha.UpdateCounterRequest request = Alpha.UpdateCounterRequest + .newBuilder() + .setCounterUpdateRequest(update) + .build(); + this.alpha.updateCounter(request, Internal.observerMap(response, Internal::toCounter)); + } + + @Override + public void setCounterCapacity(final String name, final long amount, final StreamObserver response) { + final Alpha.CounterUpdateRequest update = Alpha.CounterUpdateRequest + .newBuilder() + .setName(name) + .setCapacity(Int64Value.newBuilder().setValue(amount).build()) + .build(); + final Alpha.UpdateCounterRequest request = Alpha.UpdateCounterRequest + .newBuilder() + .setCounterUpdateRequest(update) + .build(); + this.alpha.updateCounter(request, Internal.observerMap(response, Internal::toCounter)); + } + + @Override + public void close() throws Exception { + this.channel.shutdown().awaitTermination(5L, TimeUnit.SECONDS); + } + + static final class Builder implements Agones.Builder { + + private final ManagedChannel channel; + private final ExecutorService gameServerWatcherExecutor; + private final ScheduledExecutorService healthCheckExecutor; + private final Duration healthCheckDelay; + private final Duration healthCheckPeriod; + + private Builder( + final ManagedChannel channel, + final ExecutorService gameServerWatcherExecutor, + final ScheduledExecutorService healthCheckExecutor, + final Duration healthCheckDelay, + final Duration healthCheckPeriod + ) { + this.channel = channel; + this.gameServerWatcherExecutor = gameServerWatcherExecutor; + this.healthCheckExecutor = healthCheckExecutor; + this.healthCheckDelay = healthCheckDelay; + this.healthCheckPeriod = healthCheckPeriod; + } + + Builder() { + this(null, null, null, null, null); + } + + @Override + public Agones build() { + if (this.channel == null) { + return this.withChannel().build(); + } + return new AgonesImpl(this); + } + + @Override + public Agones.Builder withChannel(final ManagedChannel channel) { + return new Builder( + channel, + this.gameServerWatcherExecutor, + this.healthCheckExecutor, + this.healthCheckDelay, + this.healthCheckPeriod + ); + } + + @Override + public Agones.Builder withGameServerWatcherExecutor(final ExecutorService executor) { + return new Builder( + this.channel, + executor, + this.healthCheckExecutor, + this.healthCheckDelay, + this.healthCheckPeriod + ); + } + + @Override + public Agones.Builder withHealthCheck(final Duration delay, final Duration period) { + return new Builder(this.channel, this.gameServerWatcherExecutor, this.healthCheckExecutor, delay, period); + } + + @Override + public Agones.Builder withHealthCheckExecutor(final ScheduledExecutorService executor) { + return new Builder( + this.channel, + this.gameServerWatcherExecutor, + executor, + this.healthCheckDelay, + this.healthCheckPeriod + ); + } + + private ScheduledExecutorService healthCheckExecutor() { + if (this.healthCheckExecutor != null) { + return this.healthCheckExecutor; + } + if (this.healthCheckDelay != null) { + return Executors.newSingleThreadScheduledExecutor(); + } + return null; + } + } +} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesList.java b/src/main/java/tr/com/infumia/agones4j/AgonesList.java new file mode 100644 index 0000000..5cc7667 --- /dev/null +++ b/src/main/java/tr/com/infumia/agones4j/AgonesList.java @@ -0,0 +1,79 @@ +package tr.com.infumia.agones4j; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.StringJoiner; + +/** + * Represents a list in the Agones system. + */ +public final class AgonesList { + + private final String name; + private final long capacity; + private final List values; + + AgonesList(final String name, final long capacity, final List values) { + this.name = name; + this.capacity = capacity; + this.values = Collections.unmodifiableList(values); + } + + /** + * Retrieves the name of the list. + * + * @return The name. + */ + public String getName() { + return this.name; + } + + /** + * Retrieves the capacity of the list. + * + * @return The capacity. + */ + public long getCapacity() { + return this.capacity; + } + + /** + * Returns the values of the list. + * + * @return the values. + */ + public List getValues() { + return this.values; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null || this.getClass() != obj.getClass()) { + return false; + } + final AgonesList that = (AgonesList) obj; + return ( + Objects.equals(this.capacity, that.capacity) && + Objects.equals(this.name, that.name) && + Objects.equals(this.values, that.values) + ); + } + + @Override + public int hashCode() { + return Objects.hash(this.name, this.capacity, this.values); + } + + @Override + public String toString() { + return new StringJoiner(", ", AgonesList.class.getSimpleName() + "[", "]") + .add("name='" + this.name + "'") + .add("capacity=" + this.capacity) + .add("values=" + this.values) + .toString(); + } +} diff --git a/src/main/java/tr/com/infumia/agones4j/AgonesSdk.java b/src/main/java/tr/com/infumia/agones4j/AgonesSdk.java deleted file mode 100644 index b74e0d4..0000000 --- a/src/main/java/tr/com/infumia/agones4j/AgonesSdk.java +++ /dev/null @@ -1,247 +0,0 @@ -package tr.com.infumia.agones4j; - -import agones.dev.sdk.SDKGrpc; -import agones.dev.sdk.Sdk; -import allocation.Allocation; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.stub.StreamObserver; -import java.util.concurrent.TimeUnit; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.experimental.Accessors; -import lombok.experimental.FieldDefaults; -import org.jetbrains.annotations.NotNull; - -/** - * a class that represents Agones Sdk. - */ -@Accessors(fluent = true) -@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) -public final class AgonesSdk implements AutoCloseable { - - /** - * the alpha. - */ - @NotNull - @Getter - AgonesAlphaSdk alpha; - - /** - * the beta. - */ - @NotNull - @Getter - AgonesBetaSdk beta; - - /** - * the channel. - */ - @NotNull - ManagedChannel channel; - - /** - * the stub. - */ - @NotNull - SDKGrpc.SDKStub stub; - - /** - * ctor. - * - * @param channel the channel. - */ - public AgonesSdk(@NotNull final ManagedChannel channel) { - this.channel = channel; - this.stub = SDKGrpc.newStub(this.channel); - this.alpha = new AgonesAlphaSdk(this.channel); - this.beta = new AgonesBetaSdk(this.channel); - } - - /** - * ctor. - * - * @param grpcHost the grpc host. - * @param grpcPort the grpc port. - */ - public AgonesSdk(@NotNull final String grpcHost, final int grpcPort) { - this( - ManagedChannelBuilder - .forAddress(grpcHost, grpcPort) - .usePlaintext() - .build() - ); - } - - /** - * ctor. - * - * @param grpcHost the grpc host. - */ - public AgonesSdk(@NotNull final String grpcHost) { - this(grpcHost, Vars.AGONES_SDK_GRPC_PORT); - } - - /** - * ctor. - * - * @param grpcPort the grpc port. - */ - public AgonesSdk(final int grpcPort) { - this("localhost", grpcPort); - } - - /** - * ctor. - */ - public AgonesSdk() { - this(Vars.AGONES_SDK_GRPC_PORT); - } - - /** - * call to self {@link Allocation} the {@link Sdk.GameServer}. - * - * @param observer the observer to call. - */ - public void allocate(@NotNull final StreamObserver observer) { - this.stub.allocate(Sdk.Empty.getDefaultInstance(), observer); - } - - @Override - public void close() throws Exception { - this.channel.shutdown().awaitTermination(5L, TimeUnit.SECONDS); - } - - /** - * retrieve the current {@link Sdk.GameServer} data. - * - * @param observer the observer to retrieve. - */ - public void getGameServer( - @NotNull final StreamObserver observer - ) { - this.stub.getGameServer(Sdk.Empty.getDefaultInstance(), observer); - } - - /** - * send a {@link Sdk.Empty} every duration to declare that this {@link Sdk.GameServer} is healthy. - * - * @param observer the observer to send. - * - * @return observer. - */ - @NotNull - public StreamObserver health( - @NotNull final StreamObserver observer - ) { - return this.stub.health(observer); - } - - /** - * call when the {@link Sdk.GameServer} is ready. - * - * @param observer the observer to call. - */ - public void ready(@NotNull final StreamObserver observer) { - this.stub.ready(Sdk.Empty.getDefaultInstance(), observer); - } - - /** - * marks the {@link Sdk.GameServer} as the Reserved state for Duration. - * - * @param duration the duration to mark. - * @param observer the observer to mark. - */ - public void reserve( - @NotNull final Sdk.Duration duration, - @NotNull final StreamObserver observer - ) { - this.stub.reserve(duration, observer); - } - - /** - * apply an Annotation to the backing {@link Sdk.GameServer} metadata. - * - * @param keyValue the key value to apply. - * @param observer the observer to apply. - */ - public void setAnnotation( - @NotNull final Sdk.KeyValue keyValue, - @NotNull final StreamObserver observer - ) { - this.stub.setAnnotation(keyValue, observer); - } - - /** - * apply an Annotation to the backing {@link Sdk.GameServer} metadata. - * - * @param key the key to apply. - * @param value the value to apply. - * @param observer the observer to apply. - * - * @see #setAnnotation(Sdk.KeyValue, StreamObserver) - */ - public void setAnnotation( - @NotNull final String key, - @NotNull final String value, - @NotNull final StreamObserver observer - ) { - this.setAnnotation( - Sdk.KeyValue.newBuilder().setKey(key).setValue(value).build(), - observer - ); - } - - /** - * apply a Label to the backing {@link Sdk.GameServer} metadata. - * - * @param keyValue the key value to apply. - * @param observer the observer to apply. - */ - public void setLabel( - @NotNull final Sdk.KeyValue keyValue, - @NotNull final StreamObserver observer - ) { - this.stub.setLabel(keyValue, observer); - } - - /** - * apply a Label to the backing {@link Sdk.GameServer} metadata. - * - * @param key the key to apply. - * @param value the value to apply. - * @param observer the observer to apply. - * - * @see #setLabel(Sdk.KeyValue, StreamObserver) - */ - public void setLabel( - @NotNull final String key, - @NotNull final String value, - @NotNull final StreamObserver observer - ) { - this.setLabel( - Sdk.KeyValue.newBuilder().setKey(key).setValue(value).build(), - observer - ); - } - - /** - * call when the {@link Sdk.GameServer} is shutting down. - * - * @param observer the observer to call. - */ - public void shutdown(@NotNull final StreamObserver observer) { - this.stub.shutdown(Sdk.Empty.getDefaultInstance(), observer); - } - - /** - * send {@link Sdk.GameServer} details whenever the {@link Sdk.GameServer} is updated. - * - * @param observer the observer to send. - */ - public void watchGameServer( - @NotNull final StreamObserver observer - ) { - this.stub.watchGameServer(Sdk.Empty.getDefaultInstance(), observer); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/Envs.java b/src/main/java/tr/com/infumia/agones4j/Envs.java deleted file mode 100644 index 6f77934..0000000 --- a/src/main/java/tr/com/infumia/agones4j/Envs.java +++ /dev/null @@ -1,149 +0,0 @@ -package tr.com.infumia.agones4j; - -import java.util.Optional; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * an interface that contains utility methods for environment variables. - */ -interface Envs { - /** - * gets the variable. - * - * @param key the key to get. - * - * @return environment variable. - */ - @Nullable - static String get(@NotNull final String key) { - return System.getenv(key); - } - - /** - * gets the variable. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable. - */ - @Nullable - @Contract("_, !null -> !null") - static String get(@NotNull final String key, @Nullable final String def) { - return Envs.getOptional(key).orElse(def); - } - - /** - * gets the variable as double. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable as double. - */ - static double getDouble(@NotNull final String key, final double def) { - return Envs.getOptional(key).flatMap(Numbers::parseDouble).orElse(def); - } - - /** - * gets the variable as float. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable as float. - */ - static float getFloat(@NotNull final String key, final float def) { - return Envs.getOptional(key).flatMap(Numbers::parseFloat).orElse(def); - } - - /** - * gets the variable as int. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable as int. - */ - static int getInt(@NotNull final String key, final int def) { - return Envs.getOptional(key).flatMap(Numbers::parseInt).orElse(def); - } - - /** - * gets the variable as long. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable as long. - */ - static long getLong(@NotNull final String key, final long def) { - return Envs.getOptional(key).flatMap(Numbers::parseLong).orElse(def); - } - - /** - * gets the variable. - * - * @param key the key to get. - * - * @return environment variable. - */ - @NotNull - static Optional getOptional(@NotNull final String key) { - return Optional.ofNullable(Envs.get(key)); - } - - /** - * gets the env. or throw. - * - * @param key the key to get. - * - * @return environment variable. - */ - @NotNull - static String getOrThrow(@NotNull final String key) { - return Exceptions.checkNotNull( - Envs.get(key), - "Env. called '%s' not found!", - key - ); - } - - /** - * gets the variable as string array. - * - * @param key the key to get. - * @param def the default to get. - * @param regex the regex to get. - * - * @return environment variable as string array. - */ - @Nullable - @Contract("_, !null, _ -> !null") - static String[] getStringArray( - @NotNull final String key, - @Nullable final String[] def, - @NotNull final String regex - ) { - return Envs.getOptional(key).map(s -> s.split(regex)).orElse(def); - } - - /** - * gets the variable as string array. - * - * @param key the key to get. - * @param def the default to get. - * - * @return environment variable as string array. - */ - @Nullable - @Contract("_, !null -> !null") - static String[] getStringArray( - @NotNull final String key, - @Nullable final String[] def - ) { - return Envs.getStringArray(key, def, ","); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/Exceptions.java b/src/main/java/tr/com/infumia/agones4j/Exceptions.java deleted file mode 100644 index fdad4eb..0000000 --- a/src/main/java/tr/com/infumia/agones4j/Exceptions.java +++ /dev/null @@ -1,143 +0,0 @@ -package tr.com.infumia.agones4j; - -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * an interface that contains utility methods for exceptions. - */ -interface Exceptions { - /** - * throws an {@link IllegalArgumentException}. - * - * @param message the message to throw. - * @param args the args to throw. - * - * @throws IllegalArgumentException anyway. - */ - @Contract("_, _ -> fail") - static void argument( - @NotNull final String message, - @NotNull final Object... args - ) throws IllegalArgumentException { - throw new IllegalArgumentException(message.formatted(args)); - } - - /** - * checks if the {@code check} is false throws {@link IllegalArgumentException}. - * - * @param check the check to check. - * @param message the message to check. - * @param args the args to check - * - * @throws IllegalArgumentException if the {@code check} is {@code false}. - */ - @Contract("false, _, _ -> fail") - static void checkArgument( - final boolean check, - @NotNull final String message, - @NotNull final Object... args - ) throws IllegalArgumentException { - if (!check) { - Exceptions.argument(message, args); - } - } - - /** - * checks if the {@code object} is null, if it's throws {@link NullPointerException} - * - * @param object the object to check. - * @param message the message to check. - * @param args the args to check. - * @param type of the object. - * - * @return the nonnull object. - * - * @throws NullPointerException if the {@code object} is null. - */ - @NotNull - @Contract("null, _, _ -> fail; !null, _, _ -> param1") - static T checkNotNull( - @Nullable final T object, - @NotNull final String message, - @NotNull final Object... args - ) throws NullPointerException { - if (object == null) { - Exceptions.nullPointer(message, args); - } - return object; - } - - /** - * checks if the {@code object} is null, if it's throws {@link NullPointerException} - * - * @param object the object to check. - * @param type of the object. - * - * @return the nonnull object. - * - * @throws NullPointerException if the {@code object} is null. - */ - @NotNull - @Contract("null -> fail; !null -> param1") - static T checkNotNull(@Nullable final T object) - throws NullPointerException { - if (object == null) { - throw new NullPointerException(); - } - return object; - } - - /** - * checks if the {@code check} is false throws {@link IllegalStateException}. - * - * @param check the check to check. - * @param message the message to check. - * @param args the args to check - * - * @throws IllegalStateException if the {@code check} is {@code false}. - */ - @Contract("false, _, _ -> fail") - static void checkState( - final boolean check, - @NotNull final String message, - @NotNull final Object... args - ) throws IllegalStateException { - if (!check) { - Exceptions.state(message, args); - } - } - - /** - * throws an {@link NullPointerException}. - * - * @param message the message to throw. - * @param args the args to throw. - * - * @throws NullPointerException anyway. - */ - @Contract("_, _ -> fail") - static void nullPointer( - @NotNull final String message, - @NotNull final Object... args - ) throws NullPointerException { - throw new NullPointerException(message.formatted(args)); - } - - /** - * throws an {@link IllegalStateException}. - * - * @param message the message to throw. - * @param args the args to throw. - * - * @throws IllegalStateException anyway. - */ - @Contract("_, _ -> fail") - static void state( - @NotNull final String message, - @NotNull final Object... args - ) throws IllegalStateException { - throw new IllegalStateException(message.formatted(args)); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/Internal.java b/src/main/java/tr/com/infumia/agones4j/Internal.java new file mode 100644 index 0000000..0950825 --- /dev/null +++ b/src/main/java/tr/com/infumia/agones4j/Internal.java @@ -0,0 +1,173 @@ +package tr.com.infumia.agones4j; + +import agones.dev.sdk.Sdk; +import agones.dev.sdk.alpha.Alpha; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Function; + +final class Internal { + + private static final int DEFAULT_GRPC_PORT = 9357; + private static final String DEFAULT_GRPC_HOST = "localhost"; + + private static final String ENV_GRPC_HOST = "AGONES_SDK_GRPC_HOST"; + private static final String ENV_GRPC_PORT = "AGONES_SDK_GRPC_PORT"; + private static final String ENV_GRPC_ADDRESS = "AGONES_SDK_GRPC_ADDRESS"; + + static final String GRPC_HOST = Internal.getEnv(Internal.ENV_GRPC_HOST, Internal.DEFAULT_GRPC_HOST); + static final int GRPC_PORT = Internal.getEnvAsInt(Internal.ENV_GRPC_PORT, Internal.DEFAULT_GRPC_PORT); + static final String GRPC_ADDRESS = Internal.getEnv(Internal.ENV_GRPC_ADDRESS, null); + + private static final StreamObserver EMPTY = new Adapter<>(); + private static final StreamObserver EMPTY_ALPHA = new Adapter<>(); + + private Internal() { + throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); + } + + static AgonesCounter toCounter(final Alpha.Counter counter) { + return new AgonesCounter(counter.getName(), counter.getCapacity(), counter.getCount()); + } + + static AgonesList toList(final Alpha.List list) { + return new AgonesList(list.getName(), list.getCapacity(), list.getValuesList()); + } + + static Alpha.List toAgonesList(final AgonesList list) { + return Alpha.List + .newBuilder() + .setName(list.getName()) + .setCapacity(list.getCapacity()) + .addAllValues(list.getValues()) + .build(); + } + + private static String getEnv(final String key, final String def) { + Objects.requireNonNull(key, "key"); + return Internal.getEnvOptional(key).orElse(def); + } + + private static int getEnvAsInt(final String key, final int def) { + Objects.requireNonNull(key, "key"); + return Internal.getEnvOptional(key).flatMap(Internal::parseInt).orElse(def); + } + + private static Optional getEnvOptional(final String key) { + Objects.requireNonNull(key, "key"); + return Optional.ofNullable(Internal.getEnv(key)); + } + + private static String getEnv(final String key) { + Objects.requireNonNull(key, "key"); + return System.getenv(key); + } + + private static Optional parseInt(final String text) { + Objects.requireNonNull(text, "text"); + try { + return Optional.of(Integer.parseInt(text)); + } catch (final Exception ignored) {} + return Optional.empty(); + } + + static StreamObserver observerEmpty() { + return Internal.EMPTY; + } + + static StreamObserver observerEmptyAlpha() { + return Internal.EMPTY_ALPHA; + } + + static CompletableFuture observerToFuture(final Consumer> response) { + final CompletableFuture future = new CompletableFuture<>(); + response.accept(new Future<>(future)); + return future; + } + + static StreamObserver observerOnNext(final Executor executor, final List> consumers) { + return new Adapter() { + @Override + public void onNext(final T value) { + executor.execute(() -> { + for (final Consumer consumer : consumers) { + consumer.accept(value); + } + }); + } + }; + } + + static StreamObserver observerMap(final StreamObserver observer, final Function mapper) { + return new Mapped<>(observer, mapper); + } + + private static final class Mapped implements StreamObserver { + + private final StreamObserver observer; + private final Function mapper; + + private Mapped(final StreamObserver observer, final Function mapper) { + this.observer = observer; + this.mapper = mapper; + } + + @Override + public void onNext(final R value) { + this.observer.onNext(this.mapper.apply(value)); + } + + @Override + public void onError(final Throwable t) { + this.observer.onError(t); + } + + @Override + public void onCompleted() { + this.observer.onCompleted(); + } + } + + private static final class Future implements StreamObserver { + + private final AtomicReference value = new AtomicReference<>(); + private final CompletableFuture future; + + private Future(final CompletableFuture future) { + this.future = future; + } + + @Override + public void onNext(final T value) { + this.value.set(value); + } + + @Override + public void onError(final Throwable t) { + this.future.completeExceptionally(t); + } + + @Override + public void onCompleted() { + this.future.complete(this.value.get()); + } + } + + private static class Adapter implements StreamObserver { + + @Override + public void onNext(final T value) {} + + @Override + public void onError(final Throwable t) {} + + @Override + public void onCompleted() {} + } +} diff --git a/src/main/java/tr/com/infumia/agones4j/Numbers.java b/src/main/java/tr/com/infumia/agones4j/Numbers.java deleted file mode 100644 index 1bf9efd..0000000 --- a/src/main/java/tr/com/infumia/agones4j/Numbers.java +++ /dev/null @@ -1,69 +0,0 @@ -package tr.com.infumia.agones4j; - -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -/** - * an interface that contains utility methods for numbers. - */ -interface Numbers { - /** - * parses the text into {@code double}. - * - * @param text the text to parse. - * - * @return parsed double. - */ - @NotNull - static Optional parseDouble(@NotNull final String text) { - try { - return Optional.of(Double.parseDouble(text)); - } catch (final Exception ignored) {} - return Optional.empty(); - } - - /** - * parses the text into {@code float}. - * - * @param text the text to parse. - * - * @return parsed float. - */ - @NotNull - static Optional parseFloat(@NotNull final String text) { - try { - return Optional.of(Float.parseFloat(text)); - } catch (final Exception ignored) {} - return Optional.empty(); - } - - /** - * parses the text into {@code int}. - * - * @param text the text to parse. - * - * @return parsed int. - */ - @NotNull - static Optional parseInt(@NotNull final String text) { - try { - return Optional.of(Integer.parseInt(text)); - } catch (final Exception ignored) {} - return Optional.empty(); - } - - /** - * parses the text into {@code long}. - * - * @param text the text to parse. - * - * @return parsed long. - */ - @NotNull - static Optional parseLong(@NotNull final String text) { - try { - return Optional.of(Long.parseLong(text)); - } catch (final Exception ignored) {} - return Optional.empty(); - } -} diff --git a/src/main/java/tr/com/infumia/agones4j/Vars.java b/src/main/java/tr/com/infumia/agones4j/Vars.java deleted file mode 100644 index 381ac5c..0000000 --- a/src/main/java/tr/com/infumia/agones4j/Vars.java +++ /dev/null @@ -1,16 +0,0 @@ -package tr.com.infumia.agones4j; - -/** - * an interface that contains environment variables. - */ -interface Vars { - /** - * the agones sdk grpc port. - */ - int AGONES_SDK_GRPC_PORT = Envs.getInt("AGONES_SDK_GRPC_PORT", 9357); - - /** - * the agones sdk http port. - */ - int AGONES_SDK_HTTP_PORT = Envs.getInt("AGONES_SDK_HTTP_PORT", 9358); -} diff --git a/src/main/java/tr/com/infumia/agones4j/package-info.java b/src/main/java/tr/com/infumia/agones4j/package-info.java deleted file mode 100644 index 4aa9b20..0000000 --- a/src/main/java/tr/com/infumia/agones4j/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * the package that contains main classes for Agones Sdk. - */ -package tr.com.infumia.agones4j; diff --git a/src/main/proto/allocation/allocation.proto b/src/main/proto/allocation/allocation.proto index b4f1b20..b180296 100644 --- a/src/main/proto/allocation/allocation.proto +++ b/src/main/proto/allocation/allocation.proto @@ -18,6 +18,7 @@ package allocation; option go_package = "./allocation"; import "google/api/annotations.proto"; +import "google/protobuf/wrappers.proto"; import "grpc-gateway/protoc-gen-openapiv2/options/annotations.proto"; option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { @@ -77,20 +78,49 @@ message AllocationRequest { // This is useful for things like smoke testing of new game servers. // Note: This field can only be set if neither Required or Preferred is set. repeated GameServerSelector gameServerSelectors = 8; + + // (Alpha, CountsAndLists feature flag) The first Priority on the array of Priorities is the most + // important for sorting. The allocator will use the first priority for sorting GameServers in the + // Selector set, and will only use any following priority for tie-breaking during sort. + // Impacts which GameServer is checked first. + repeated Priority priorities = 9; + + // (Alpha, CountsAndLists feature flag) Counters and Lists provide a set of actions to perform + // on Counters and Lists during allocation. + map counters = 10; + map lists = 11; } message AllocationResponse { string gameServerName = 2; repeated GameServerStatusPort ports = 3; + + // Primary address at which game server can be reached string address = 4; + + // All addresses at which game server can be reached; copy of Node.Status.addresses + repeated GameServerStatusAddress addresses = 8; + string nodeName = 5; string source = 6; + optional GameServerMetadata metadata = 7; // The gameserver port info that is allocated. message GameServerStatusPort { string name = 1; int32 port = 2; } + + // A single address; identical to corev1.NodeAddress + message GameServerStatusAddress { + string type = 1; + string address = 2; + } + + message GameServerMetadata { + map labels = 1; + map annotations = 2; + } } // Specifies settings for multi-cluster allocation. @@ -124,6 +154,8 @@ message GameServerSelector { }; GameServerState gameServerState = 2; PlayerSelector players = 3; + map counters = 4; + map lists = 5; } // PlayerSelector is filter for player capacity values. @@ -132,3 +164,59 @@ message PlayerSelector { uint64 minAvailable = 1; uint64 maxAvailable = 2; } + +// CounterSelector is the filter options for a GameServer based on the count and/or available capacity. +// 0 for MaxCount or MaxAvailable means unlimited maximum. Default for all fields: 0 +message CounterSelector { + int64 minCount = 1; + int64 maxCount = 2; + int64 minAvailable = 3; + int64 maxAvailable = 4; +} + +// ListSelector is the filter options for a GameServer based on List available capacity and/or the +// existence of a value in a List. +// 0 for MaxAvailable means unlimited maximum. Default for integer fields: 0 +// "" for ContainsValue means ignore field. Default for string field: "" +message ListSelector { + string containsValue = 1; + int64 minAvailable = 2; + int64 maxAvailable = 3; +} + +// Priority is a sorting option for GameServers with Counters or Lists based on the Capacity. +// Type: Sort by a "Counter" or a "List". +// Key: The name of the Counter or List. If not found on the GameServer, has no impact. +// Order: Sort by "Ascending" or "Descending". "Descending" a bigger Capacity is preferred. +// "Ascending" would be smaller Capacity is preferred. +message Priority { + enum Type { + Counter = 0; + List = 1; + } + Type type = 1; + string key = 2; + enum Order { + Ascending = 0; + Descending = 1; + } + Order order = 3; +} + +// CounterAction is an optional action that can be performed on a Counter at allocation. +// Action: "Increment" or "Decrement" the Counter's Count (optional). Must also define the Amount. +// Amount: The amount to increment or decrement the Count (optional). Must be a positive integer. +// Capacity: Update the maximum capacity of the Counter to this number (optional). Min 0, Max int64. +message CounterAction { + google.protobuf.StringValue action = 1; + google.protobuf.Int64Value amount = 2; + google.protobuf.Int64Value capacity = 3; +} + +// ListAction is an optional action that can be performed on a List at allocation. +// AddValues: Append values to a List's Values array (optional). Any duplicate values will be ignored. +// Capacity: Update the maximum capacity of the Counter to this number (optional). Min 0, Max 1000. +message ListAction { + repeated string addValues = 1; + google.protobuf.Int64Value capacity = 2; +} diff --git a/src/main/proto/sdk/alpha/alpha.proto b/src/main/proto/sdk/alpha/alpha.proto index d255923..1f4cc33 100644 --- a/src/main/proto/sdk/alpha/alpha.proto +++ b/src/main/proto/sdk/alpha/alpha.proto @@ -23,6 +23,7 @@ import "google/api/field_behavior.proto"; import "google/api/resource.proto"; import "google/protobuf/empty.proto"; import "google/protobuf/field_mask.proto"; +import "google/protobuf/wrappers.proto"; import "grpc-gateway/protoc-gen-openapiv2/options/annotations.proto"; option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { @@ -131,28 +132,25 @@ service SDK { // Gets a Counter. Returns NOT_FOUND if the Counter does not exist. rpc GetCounter(GetCounterRequest) returns (Counter) { option (google.api.http) = { - get: "/v1alpha1/{name=counters/*}" + get: "/v1alpha1/counters/{name}" }; option (google.api.method_signature) = "name"; } // UpdateCounter returns the updated Counter. Returns NOT_FOUND if the Counter does not exist (name cannot be updated). // Returns OUT_OF_RANGE if the Count is out of range [0,Capacity]. - // Returns INVALID_ARGUMENT if the field mask path(s) are not field(s) of the Counter. - // If a field mask path(s) is specified, but the value is not set in the request Counter object, - // then the default value for the variable will be set (i.e. 0 for "capacity" or "count"). rpc UpdateCounter(UpdateCounterRequest) returns (Counter) { option (google.api.http) = { - patch: "/v1alpha1/{counter.name=counters/*}" - body: "counter" + patch: "/v1alpha1/counters/{counterUpdateRequest.name}" + body: "counterUpdateRequest" }; - option (google.api.method_signature) = "counter,update_mask"; + option (google.api.method_signature) = "counterUpdateRequest"; } // Gets a List. Returns NOT_FOUND if the List does not exist. rpc GetList(GetListRequest) returns (List) { option (google.api.http) = { - get: "/v1alpha1/{name=lists/*}" + get: "/v1alpha1/lists/{name}" }; option (google.api.method_signature) = "name"; } @@ -165,7 +163,7 @@ service SDK { // then the default value for the variable will be set (i.e. 0 for "capacity", empty list for "values"). rpc UpdateList(UpdateListRequest) returns (List) { option (google.api.http) = { - patch: "/v1alpha1/{list.name=lists/*}" + patch: "/v1alpha1/lists/{list.name}" body: "list" }; option (google.api.method_signature) = "list,update_mask"; @@ -176,7 +174,7 @@ service SDK { // Returns OUT_OF_RANGE if the List is already at Capacity. rpc AddListValue(AddListValueRequest) returns (List) { option (google.api.http) = { - post: "/v1alpha1/{name=lists/*}:addValue" + post: "/v1alpha1/lists/{name}:addValue" body: "*" }; } @@ -185,7 +183,7 @@ service SDK { // Returns NOT_FOUND if the value is not in the List. rpc RemoveListValue(RemoveListValueRequest) returns (List) { option (google.api.http) = { - post: "/v1alpha1/{name=lists/*}:removeValue" + post: "/v1alpha1/lists/{name}:removeValue" body: "*" }; } @@ -229,6 +227,23 @@ message Counter { int64 capacity = 3; } +// A representation of a Counter Update Request. +message CounterUpdateRequest { + option (google.api.resource) = { + type: "agones.dev/CounterUpdateRequest" + pattern: "counterUpdateRequests/{counterUpdateRequest}" + }; + // The name of the Counter to update + string name = 1; + // The value to set the Counter Count + google.protobuf.Int64Value count = 2; + // The value to set the Counter Capacity + google.protobuf.Int64Value capacity = 3; + // countDiff tracks if a Counter Update Request is CountIncrement (positive), CountDecrement + // (negative), 0 if a CountSet or CapacitySet request + int64 countDiff = 4; +} + message GetCounterRequest { // The name of the Counter to get string name = 1 [ @@ -239,17 +254,12 @@ message GetCounterRequest { } message UpdateCounterRequest { - // The Counter to update - Counter counter = 1 [ + // The requested update to make to the Counter + CounterUpdateRequest counterUpdateRequest = 1 [ (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = { - type: "agones.dev/Counter" + type: "agones.dev/CounterUpdateRequest" }]; - - // Required. Mask (list) of fields to update. - // Fields are specified relative to the Counter - // (e.g. `count`, `capacity`; *not* `Counter.count` or `Counter.capacity`). - google.protobuf.FieldMask update_mask = 2 [(google.api.field_behavior) = REQUIRED]; } // A representation of a List. diff --git a/src/main/proto/sdk/beta/beta.proto b/src/main/proto/sdk/beta/beta.proto index bdb1ec0..02ec501 100644 --- a/src/main/proto/sdk/beta/beta.proto +++ b/src/main/proto/sdk/beta/beta.proto @@ -31,4 +31,4 @@ option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = { }; // SDK service to be used in the GameServer SDK to the Pod Sidecar -service SDK {} \ No newline at end of file +service SDK {} diff --git a/src/main/proto/sdk/sdk.proto b/src/main/proto/sdk/sdk.proto index df5b499..9f5ff68 100644 --- a/src/main/proto/sdk/sdk.proto +++ b/src/main/proto/sdk/sdk.proto @@ -150,6 +150,11 @@ message GameServer { } message Status { + message Address { + string type = 1; + string address = 2; + } + message Port { string name = 1; int32 port = 2; @@ -178,6 +183,7 @@ message GameServer { string state = 1; string address = 2; + repeated Address addresses = 7; repeated Port ports = 3; // [Stage:Alpha]