Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -103,6 +104,22 @@ public Instance status(int players, int maxPlayers, Map<String, String> 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<NetworkStatus> 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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
Original file line number Diff line number Diff line change
@@ -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<String> 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<NetworkStatus> 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<NetworkStatus> 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");
}
}
}
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -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());
}

Expand All @@ -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;
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -179,17 +204,20 @@ 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
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()) {
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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));
}));
}
}
Loading