diff --git a/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java index 588a65c..678994b 100644 --- a/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java +++ b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/GrusClient.java @@ -15,6 +15,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; /** * Blocking client for the Grus REST API ({@code /v1}). Thread-safe. @@ -103,6 +104,22 @@ public Instance status(int players, int maxPlayers, Map labels) return read(send("PUT", "/v1/self/status", Map.of(), toJson(body)), Instance.class); } + /** + * Network-wide player count ({@code GET /v1/network}). + * + * @return the count, or empty when the controller answers 404 because it predates the endpoint + */ + public Optional network() { + try { + return Optional.of(read(send("GET", "/v1/network", Map.of(), null), NetworkStatus.class)); + } catch (GrusException e) { + if (e.status() == 404) { + return Optional.empty(); + } + throw e; + } + } + /** Marks this instance as allocated to a player group ({@code POST /v1/self/allocate}). */ public Instance allocate() { return read(send("POST", "/v1/self/allocate", Map.of(), null), Instance.class); diff --git a/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/NetworkStatus.java b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/NetworkStatus.java new file mode 100644 index 0000000..20d153a --- /dev/null +++ b/java/grus-sdk/src/main/java/net/onelitefeather/grus/sdk/NetworkStatus.java @@ -0,0 +1,32 @@ +package net.onelitefeather.grus.sdk; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * Network-wide player count as returned by {@code GET /v1/network} and published as the + * {@value #EVENT_TYPE} event. + * + * @param players players on all Ready or Allocated proxies + * @param maxPlayers capacity of those proxies + * @param proxies number of proxies counted + */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record NetworkStatus(int players, int maxPlayers, int proxies) { + + /** SSE event name; subscribe with {@code EventStream.start(..., List.of(NetworkStatus.EVENT_TYPE), ...)}. */ + public static final String EVENT_TYPE = "network.players"; + + /** + * Parses the data of a {@value #EVENT_TYPE} event. + * + * @throws IllegalArgumentException when the payload does not match this shape + */ + public static NetworkStatus from(GrusEvent event) { + try { + return Json.MAPPER.treeToValue(event.data(), NetworkStatus.class); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new IllegalArgumentException("not a network status payload: " + event.type(), e); + } + } +} diff --git a/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/GrusClientNetworkTest.java b/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/GrusClientNetworkTest.java new file mode 100644 index 0000000..e85127a --- /dev/null +++ b/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/GrusClientNetworkTest.java @@ -0,0 +1,56 @@ +package net.onelitefeather.grus.sdk; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class GrusClientNetworkTest { + + @Test + void networkReadsNetworkStatusFromGetV1Network() throws IOException { + try (StubServer server = new StubServer()) { + AtomicReference method = new AtomicReference<>(); + server.route("/v1/network", exchange -> { + method.set(exchange.getRequestMethod()); + StubServer.respond(exchange, 200, "{\"players\":42,\"maxPlayers\":1000,\"proxies\":3}"); + }); + GrusClient client = new GrusClient(server.config()); + + Optional status = client.network(); + + assertEquals("GET", method.get(), "the network count is read with GET"); + assertEquals(Optional.of(new NetworkStatus(42, 1000, 3)), status, "the body must be parsed"); + } + } + + @Test + void networkIsEmptyWhenControllerPredatesTheEndpoint() throws IOException { + try (StubServer server = new StubServer()) { + server.route("/v1/network", exchange -> StubServer.respond(exchange, 404, "{\"error\":\"not found\"}")); + GrusClient client = new GrusClient(server.config()); + + Optional status = client.network(); + + assertFalse(status.isPresent(), "a 404 from an older controller must mean no data, not a failure"); + } + } + + @Test + void networkPropagatesServerErrors() throws IOException { + try (StubServer server = new StubServer()) { + server.route("/v1/network", exchange -> StubServer.respond(exchange, 500, "boom")); + GrusClient client = new GrusClient(server.config()); + + GrusException error = assertThrows(GrusException.class, client::network, + "only a 404 is treated as missing; other failures must reach the caller"); + + assertEquals(500, error.status(), "the HTTP status must be kept"); + } + } +} diff --git a/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/NetworkStatusTest.java b/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/NetworkStatusTest.java new file mode 100644 index 0000000..e0f974e --- /dev/null +++ b/java/grus-sdk/src/test/java/net/onelitefeather/grus/sdk/NetworkStatusTest.java @@ -0,0 +1,43 @@ +package net.onelitefeather.grus.sdk; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NetworkStatusTest { + + @Test + void parsesNetworkPlayersEventPayload() throws Exception { + GrusEvent event = event("{\"players\":42,\"maxPlayers\":1000,\"proxies\":3}"); + + NetworkStatus status = NetworkStatus.from(event); + + assertEquals(new NetworkStatus(42, 1000, 3), status, "players, maxPlayers and proxies must be parsed"); + } + + @Test + void ignoresFieldsThatAreNotKnownYet() throws Exception { + GrusEvent event = event("{\"players\":1,\"maxPlayers\":2,\"proxies\":1,\"generation\":9}"); + + assertEquals(new NetworkStatus(1, 2, 1), NetworkStatus.from(event), + "a newer controller may add fields; the SDK must still read the known ones"); + } + + @Test + void payloadThatIsNotAnObjectIsRejected() throws Exception { + GrusEvent event = event("\"not a network status\""); + + assertThrows(IllegalArgumentException.class, () -> NetworkStatus.from(event), + "a malformed network.players payload must be reported, not parsed into zeros"); + } + + @Test + void eventTypeConstantMatchesControllerContract() { + assertEquals("network.players", NetworkStatus.EVENT_TYPE, "the controller publishes this SSE event name"); + } + + private static GrusEvent event(String json) throws Exception { + return new GrusEvent("1", NetworkStatus.EVENT_TYPE, Json.MAPPER.readTree(json)); + } +} diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/BackendPing.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/BackendPing.java new file mode 100644 index 0000000..691140a --- /dev/null +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/BackendPing.java @@ -0,0 +1,20 @@ +package net.onelitefeather.grus.velocity; + +import java.util.concurrent.CompletionException; + +/** Log lines for the one-off ping of a backend server after it was registered. */ +final class BackendPing { + + private BackendPing() { + } + + static String pinged(String name, String address, String versionName, int online, int max) { + return "pinged " + name + " at " + address + ": " + versionName + " " + online + "/" + max; + } + + static String failed(String name, Throwable error) { + Throwable cause = error instanceof CompletionException && error.getCause() != null ? error.getCause() : error; + String reason = cause.getMessage() == null ? cause.getClass().getName() : cause.getMessage(); + return "ping " + name + " failed: " + reason; + } +} diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GameServers.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GameServers.java index b85a57d..60a5ed3 100644 --- a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GameServers.java +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GameServers.java @@ -142,6 +142,7 @@ private void register(String id, String address) { registry.registerServer(id, target); owned.put(id, address); LOG.info("registered {} at {}", id, address); + registry.pingOnce(id); } private void unregister(String id) { diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java index 7f7e480..0c93e1b 100644 --- a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/GrusVelocity.java @@ -8,6 +8,7 @@ import com.velocitypowered.api.event.player.KickedFromServerEvent; import com.velocitypowered.api.event.player.PlayerChooseInitialServerEvent; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.event.proxy.ProxyPingEvent; import com.velocitypowered.api.event.proxy.ProxyShutdownEvent; import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.proxy.ProxyServer; @@ -20,6 +21,7 @@ import net.onelitefeather.grus.sdk.GrusException; import net.onelitefeather.grus.sdk.Instance; import net.onelitefeather.grus.sdk.InstanceStateChange; +import net.onelitefeather.grus.sdk.NetworkStatus; import net.onelitefeather.grus.sdk.SelfReporter; import org.slf4j.Logger; @@ -70,17 +72,19 @@ public void onInitialize(ProxyInitializeEvent event) { } GrusClient client = new GrusClient(config.get()); GameServers servers = new GameServers(new VelocityProxyRegistry(proxy)); + NetworkPlayers network = new NetworkPlayers(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( Thread.ofPlatform().name("grus-self-reporter").daemon(true).factory()); SelfReporter reporter = new SelfReporter(client, proxy::getPlayerCount, maxPlayersFromEnv(), scheduler); // The stream starts first; its onConnected callback runs the full sync once the connection is up. - EventStream stream = EventStream.start(config.get(), List.of("instance.*"), new Listener(client, servers), - Backoff.defaults()); + EventStream stream = EventStream.start(config.get(), + List.of("instance.*", NetworkStatus.EVENT_TYPE), + new Listener(client, servers, network), Backoff.defaults()); Thread.ofVirtual().name("grus-ready").start(() -> reportReady(client)); reporter.start(); - integration = new Integration(servers, reporter, stream, scheduler, fallbackPool()); + integration = new Integration(servers, network, reporter, stream, scheduler, fallbackPool()); logger.info("Grus integration enabled for instance {}", config.get().instance()); } @@ -101,6 +105,17 @@ public void onPostLogin(PostLoginEvent event) { } } + /** Shows the network-wide count in the server list; the max player count stays as Velocity has it. */ + @Subscribe + public void onProxyPing(ProxyPingEvent event) { + Integration current = integration; + if (current == null) { + return; + } + int shown = NetworkPlayers.shownOnline(current.network().players(), proxy.getPlayerCount()); + event.setPing(event.getPing().asBuilder().onlinePlayers(shown).build()); + } + @Subscribe public void onDisconnect(DisconnectEvent event) { Integration current = integration; @@ -144,12 +159,22 @@ private void reportReady(GrusClient client) { } } - private void fullSync(GrusClient client, GameServers servers) { + private void fullSync(GrusClient client, GameServers servers, NetworkPlayers network) { try { servers.sync(client.instances(null, null, GameServers.ROLE_GAME)); } catch (GrusException e) { logger.warn("Grus full sync failed with status {}: {}", e.status(), e.getMessage()); } + refreshNetwork(client, network); + } + + /** Keeps the cached network count when the controller has no endpoint for it (404 leaves it unchanged). */ + private void refreshNetwork(GrusClient client, NetworkPlayers network) { + try { + client.network().ifPresent(network::update); + } catch (GrusException e) { + logger.warn("Grus network count refresh failed with status {}: {}", e.status(), e.getMessage()); + } } private static String fallbackPool() { @@ -179,10 +204,12 @@ private final class Listener implements EventStream.Listener { private final GrusClient client; private final GameServers servers; + private final NetworkPlayers network; - Listener(GrusClient client, GameServers servers) { + Listener(GrusClient client, GameServers servers, NetworkPlayers network) { this.client = client; this.servers = servers; + this.network = network; } @Override @@ -190,6 +217,7 @@ public void onEvent(GrusEvent event) { switch (event.type()) { case "instance.state" -> servers.applyStateChange(InstanceStateChange.from(event)); case "instance.created", "instance.updated" -> servers.applyInstance(Instance.from(event)); + case NetworkStatus.EVENT_TYPE -> network.update(NetworkStatus.from(event)); case "instance.removed" -> { JsonNode id = event.data().get("instance"); if (id != null && id.isTextual()) { @@ -204,18 +232,19 @@ public void onEvent(GrusEvent event) { @Override public void onResync() { - fullSync(client, servers); + fullSync(client, servers, network); } @Override public void onConnected() { - fullSync(client, servers); + fullSync(client, servers, network); } } /** Everything that exists only while the integration is enabled. */ private record Integration( GameServers servers, + NetworkPlayers network, SelfReporter reporter, EventStream stream, ScheduledExecutorService scheduler, diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/NetworkPlayers.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/NetworkPlayers.java new file mode 100644 index 0000000..9968de9 --- /dev/null +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/NetworkPlayers.java @@ -0,0 +1,25 @@ +package net.onelitefeather.grus.velocity; + +import net.onelitefeather.grus.sdk.NetworkStatus; + +/** + * Last known network-wide player count. Written from the event stream and the initial GET, read from + * Velocity's ping handler, so it is volatile rather than synchronized. + */ +final class NetworkPlayers { + + private volatile int players; + + /** The online count to show in the server list: the network total, never less than this proxy's own players. */ + static int shownOnline(int networkPlayers, int localPlayers) { + return Math.max(networkPlayers, localPlayers); + } + + void update(NetworkStatus status) { + players = status.players(); + } + + int players() { + return players; + } +} diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/ProxyRegistry.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/ProxyRegistry.java index 5301c7a..9d283c8 100644 --- a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/ProxyRegistry.java +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/ProxyRegistry.java @@ -9,4 +9,7 @@ public interface ProxyRegistry { void registerServer(String name, HostPort address); void unregisterServer(String name); + + /** Pings a registered server once in the background and logs the result. Never throws. */ + void pingOnce(String name); } diff --git a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/VelocityProxyRegistry.java b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/VelocityProxyRegistry.java index fcf4ad1..7bda930 100644 --- a/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/VelocityProxyRegistry.java +++ b/java/grus-velocity/src/main/java/net/onelitefeather/grus/velocity/VelocityProxyRegistry.java @@ -3,11 +3,16 @@ import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.server.ServerInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetSocketAddress; /** {@link ProxyRegistry} backed by Velocity's live server list. */ final class VelocityProxyRegistry implements ProxyRegistry { + private static final Logger LOG = LoggerFactory.getLogger(VelocityProxyRegistry.class); + private final ProxyServer proxy; VelocityProxyRegistry(ProxyServer proxy) { @@ -28,4 +33,18 @@ public void registerServer(String name, HostPort address) { public void unregisterServer(String name) { proxy.getServer(name).ifPresent(server -> proxy.unregisterServer(server.getServerInfo())); } + + @Override + public void pingOnce(String name) { + proxy.getServer(name).ifPresent(server -> server.ping().whenComplete((ping, error) -> { + if (error != null) { + LOG.info(BackendPing.failed(name, error)); + return; + } + int online = ping.getPlayers().map(players -> players.getOnline()).orElse(0); + int max = ping.getPlayers().map(players -> players.getMax()).orElse(0); + String version = ping.getVersion() == null ? "unknown" : ping.getVersion().getName(); + LOG.info(BackendPing.pinged(name, server.getServerInfo().getAddress().toString(), version, online, max)); + })); + } } diff --git a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/BackendPingTest.java b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/BackendPingTest.java new file mode 100644 index 0000000..edfa2b7 --- /dev/null +++ b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/BackendPingTest.java @@ -0,0 +1,35 @@ +package net.onelitefeather.grus.velocity; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.concurrent.CompletionException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BackendPingTest { + + @Test + void successLineNamesServerAddressVersionAndCounts() { + assertEquals("pinged lobby-1 at 10.0.12.34:25565: 1.21.4 3/20", + BackendPing.pinged("lobby-1", "10.0.12.34:25565", "1.21.4", 3, 20)); + } + + @Test + void failureLineCarriesTheReason() { + assertEquals("ping lobby-1 failed: Connection refused", + BackendPing.failed("lobby-1", new IOException("Connection refused"))); + } + + @Test + void failureLineUnwrapsCompletionException() { + assertEquals("ping lobby-1 failed: Connection refused", + BackendPing.failed("lobby-1", new CompletionException(new IOException("Connection refused")))); + } + + @Test + void failureWithoutMessageUsesExceptionClassName() { + assertEquals("ping lobby-1 failed: java.io.IOException", + BackendPing.failed("lobby-1", new IOException())); + } +} diff --git a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/FakeProxyRegistry.java b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/FakeProxyRegistry.java index 8d74622..07103e7 100644 --- a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/FakeProxyRegistry.java +++ b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/FakeProxyRegistry.java @@ -10,6 +10,7 @@ final class FakeProxyRegistry implements ProxyRegistry { private final Map servers = new HashMap<>(); private final List calls = new ArrayList<>(); + private final List pings = new ArrayList<>(); /** A server that exists before Grus touches the list, like one from velocity.toml. */ FakeProxyRegistry withStaticServer(String name, HostPort address) { @@ -34,6 +35,15 @@ public void unregisterServer(String name) { calls.add("unregister " + name); } + @Override + public void pingOnce(String name) { + pings.add(name); + } + + List pings() { + return List.copyOf(pings); + } + List calls() { return List.copyOf(calls); } diff --git a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/GameServersTest.java b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/GameServersTest.java index 7c0d7f2..c9fb6cd 100644 --- a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/GameServersTest.java +++ b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/GameServersTest.java @@ -51,6 +51,29 @@ void serverWithExistingNameIsNotTouched() { assertEquals(new HostPort("127.0.0.1", 30000), proxy.address("lobby-1"), "the static server must stay as it was"); } + @Test + void newlyRegisteredServerIsPingedOnce() { + FakeProxyRegistry proxy = new FakeProxyRegistry(); + GameServers servers = new GameServers(proxy); + + servers.applyStateChange(change("lobby-1", "Starting", "Ready", ADDRESS)); + servers.applyStateChange(change("lobby-1", "Ready", "Ready", ADDRESS)); + + assertEquals(List.of("lobby-1"), proxy.pings(), + "the backend must be pinged once after registration, not on every update"); + } + + @Test + void serverThatIsNotRegisteredIsNotPinged() { + FakeProxyRegistry proxy = new FakeProxyRegistry() + .withStaticServer("lobby-1", new HostPort("127.0.0.1", 30000)); + GameServers servers = new GameServers(proxy); + + servers.applyStateChange(change("lobby-1", "Starting", "Ready", ADDRESS)); + + assertEquals(List.of(), proxy.pings(), "a server that was not registered by Grus must not be pinged"); + } + @Test void drainingStateUnregistersOwnedServer() { FakeProxyRegistry proxy = new FakeProxyRegistry(); diff --git a/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/NetworkPlayersTest.java b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/NetworkPlayersTest.java new file mode 100644 index 0000000..bdd8db1 --- /dev/null +++ b/java/grus-velocity/src/test/java/net/onelitefeather/grus/velocity/NetworkPlayersTest.java @@ -0,0 +1,40 @@ +package net.onelitefeather.grus.velocity; + +import net.onelitefeather.grus.sdk.NetworkStatus; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class NetworkPlayersTest { + + @Test + void shownOnlineIsNetworkCountWhenItIsLargerThanLocal() { + assertEquals(42, NetworkPlayers.shownOnline(42, 5), "the ping must show the whole network"); + } + + @Test + void shownOnlineIsLocalCountWhenNetworkCountLagsBehind() { + assertEquals(25, NetworkPlayers.shownOnline(10, 25), + "players who joined after the last network update must still be counted"); + } + + @Test + void shownOnlineFallsBackToLocalCountWhenNetworkIsUnknown() { + assertEquals(7, NetworkPlayers.shownOnline(0, 7), + "without a network count (404 or not yet fetched) the local count is shown"); + } + + @Test + void updateReplacesTheCachedNetworkCount() { + NetworkPlayers cache = new NetworkPlayers(); + cache.update(new NetworkStatus(42, 1000, 3)); + cache.update(new NetworkStatus(17, 1000, 3)); + + assertEquals(17, cache.players(), "the latest network.players event wins"); + } + + @Test + void cacheStartsAtZero() { + assertEquals(0, new NetworkPlayers().players(), "nothing is known before the first GET or event"); + } +}