From 723764a782f5e757bd76cabaa776741ea8f44622 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 11:31:27 +0100 Subject: [PATCH] Show server CPU and heap use in the studio status bar The bridge sends a usage event every second and when a studio connects: CPU with 100 per busy thread, like top, and the Java heap in use. The status bar shows both beside the cursor and turns each warning-coloured at 80%. v3: e1e158364 11e4ba0b1 268e72b9c 275b5965b --- .../iris/core/studio/bridge/ServerUsage.java | 51 +++++++++++++++++++ .../iris/core/studio/bridge/StudioEvents.java | 14 ++++- .../core/studio/bridge/ServerUsageTest.java | 38 ++++++++++++++ .../core/studio/bridge/StudioBridgeTest.java | 18 +++++++ .../src/renderer/src/bridge/BridgeClient.ts | 4 ++ studio/src/renderer/src/bridge/types.ts | 10 ++++ studio/src/renderer/src/studio/MapStudio.tsx | 13 +++-- studio/src/renderer/src/studio/StatusBar.tsx | 45 +++++++++++++++- .../renderer/src/studio/serverUsage.test.ts | 31 +++++++++++ studio/src/renderer/src/studio/serverUsage.ts | 27 ++++++++++ 10 files changed, 243 insertions(+), 8 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/studio/bridge/ServerUsage.java create mode 100644 core/src/test/java/art/arcane/iris/core/studio/bridge/ServerUsageTest.java create mode 100644 studio/src/renderer/src/studio/serverUsage.test.ts create mode 100644 studio/src/renderer/src/studio/serverUsage.ts diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/ServerUsage.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/ServerUsage.java new file mode 100644 index 000000000..fed5afab5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/ServerUsage.java @@ -0,0 +1,51 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.studio.bridge; + +import java.lang.management.ManagementFactory; +import java.lang.management.OperatingSystemMXBean; + +/** + * What the server asks of its machine: CPU counted like {@code top}, where 100 is one thread kept busy, and the Java + * heap in use. + * + * @param cpuPercent the process's CPU use with 100 per busy thread, or null when the JVM cannot tell + * @param threads the threads the server's CPU has, so the studio can show the most {@code cpuPercent} can reach + * @param heapUsedBytes the Java heap in use + * @param heapMaxBytes the most the Java heap can grow to + */ +record ServerUsage(Double cpuPercent, int threads, long heapUsedBytes, long heapMaxBytes) { + private static final double PERCENT_PER_THREAD = 100D; + + static ServerUsage sample() { + Runtime runtime = Runtime.getRuntime(); + OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean(); + return of(processCpuLoad(system), runtime.availableProcessors(), runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory()); + } + + /** @param processCpuLoad the share of every core the process uses, or below zero when unknown */ + static ServerUsage of(double processCpuLoad, int threads, long heapUsedBytes, long heapMaxBytes) { + Double cpuPercent = processCpuLoad < 0D ? null : processCpuLoad * threads * PERCENT_PER_THREAD; + return new ServerUsage(cpuPercent, threads, heapUsedBytes, heapMaxBytes); + } + + private static double processCpuLoad(OperatingSystemMXBean system) { + return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java index 43895a921..8c07e12ae 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioEvents.java @@ -32,22 +32,26 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * Server-sent events to every connected studio: {@code players} when a player moves, {@code world} when the world's - * engine changes (a hotload), and a comment now and then so a dead connection is noticed. A studio that stops + * engine changes (a hotload), {@code usage} with the server's CPU and heap every second, and a comment now and then so + * a dead connection is noticed. A studio that stops * reading is dropped. */ final class StudioEvents { private static final byte[] KEEP_ALIVE = ": alive\n\n".getBytes(StandardCharsets.UTF_8); static final long POLL_INTERVAL_MILLIS = 250L; private static final long KEEP_ALIVE_INTERVAL_MILLIS = 10_000L; + private static final long USAGE_INTERVAL_MILLIS = 1_000L; private final StudioWorld world; private final Gson gson; private final List listeners = new CopyOnWriteArrayList<>(); private final AtomicBoolean listenerJoined = new AtomicBoolean(); + private final AtomicBoolean usageWanted = new AtomicBoolean(); private final AtomicBoolean hotloaded = new AtomicBoolean(); private List lastPlayers; private Engine lastEngine; private long lastSentMillis; + private long lastUsageMillis; StudioEvents(StudioWorld world, Gson gson) { this.world = world; @@ -57,6 +61,7 @@ final class StudioEvents { void listen(OutputStream stream) { listeners.add(stream); listenerJoined.set(true); + usageWanted.set(true); } /** The pack was hotloaded; the engine may be the same, its streams are not. */ @@ -80,7 +85,12 @@ final class StudioEvents { lastPlayers = players; send("players", players); } - if (System.currentTimeMillis() - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) { + long now = System.currentTimeMillis(); + if (usageWanted.getAndSet(false) || now - lastUsageMillis >= USAGE_INTERVAL_MILLIS) { + lastUsageMillis = now; + send("usage", ServerUsage.sample()); + } + if (now - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) { sendToAll(KEEP_ALIVE); } } diff --git a/core/src/test/java/art/arcane/iris/core/studio/bridge/ServerUsageTest.java b/core/src/test/java/art/arcane/iris/core/studio/bridge/ServerUsageTest.java new file mode 100644 index 000000000..0589e3606 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/bridge/ServerUsageTest.java @@ -0,0 +1,38 @@ +package art.arcane.iris.core.studio.bridge; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class ServerUsageTest { + @Test + public void cpuCountsAHundredPercentPerBusyThread() { + ServerUsage usage = ServerUsage.of(0.25D, 8, 1L, 2L); + + assertEquals(200D, usage.cpuPercent(), 1e-9D); + assertEquals(8, usage.threads()); + } + + @Test + public void everyThreadBusyReachesAHundredPerThread() { + assertEquals(1600D, ServerUsage.of(1D, 16, 1L, 2L).cpuPercent(), 1e-9D); + } + + @Test + public void anUnknownCpuLoadIsLeftOut() { + assertNull(ServerUsage.of(-1D, 8, 1L, 2L).cpuPercent()); + } + + @Test + public void aSampleHoldsTheHeapInUseWithinItsMaximum() { + ServerUsage usage = ServerUsage.sample(); + + assertNotNull(usage); + assertTrue(usage.threads() >= 1); + assertTrue(usage.heapUsedBytes() > 0L); + assertTrue(usage.heapUsedBytes() <= usage.heapMaxBytes()); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java index 5ca00049f..4ecc6a680 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/bridge/StudioBridgeTest.java @@ -211,6 +211,24 @@ public class StudioBridgeTest { } } + @Test + public void aNewListenerHearsTheServersUsageRightAway() throws Exception { + HttpResponse events = http.send(authorized("events"), HttpResponse.BodyHandlers.ofInputStream()); + + try (BufferedReader lines = new BufferedReader(new InputStreamReader(events.body(), StandardCharsets.UTF_8))) { + String line; + do { + line = lines.readLine(); + } while (line != null && !line.equals("event: usage")); + assertEquals("event: usage", line); + JsonObject usage = JsonParser.parseString(lines.readLine().substring("data: ".length())).getAsJsonObject(); + assertTrue(usage.get("threads").getAsInt() >= 1); + assertTrue(usage.get("heapUsedBytes").getAsLong() > 0L); + assertTrue(usage.get("heapMaxBytes").getAsLong() >= usage.get("heapUsedBytes").getAsLong()); + assertTrue(usage.has("cpuPercent")); + } + } + private HttpResponse get(String endpoint) throws Exception { return http.send(authorized(endpoint), HttpResponse.BodyHandlers.ofString()); } diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index ff6752e69..229cbd344 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -22,6 +22,7 @@ import type { SavedWorldInfo, SceneEntry, SceneViewInfo, + ServerUsage, WorldInfo } from './types' @@ -77,6 +78,7 @@ export interface WorldRect { export interface BridgeEvents { onWorld(running: boolean): void onPlayers(players: Marker[]): void + onUsage(usage: ServerUsage): void onClosed(): void } @@ -307,5 +309,7 @@ function dispatch(block: string, events: BridgeEvents): void { events.onWorld((JSON.parse(data) as { running: boolean }).running) } else if (name === 'players') { events.onPlayers(JSON.parse(data) as Marker[]) + } else if (name === 'usage') { + events.onUsage(JSON.parse(data) as ServerUsage) } } diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index cbc50978b..e42774221 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -304,6 +304,16 @@ export interface Marker { maxHealth: number } +/** What the server asks of its machine, as it sends it every second. */ +export interface ServerUsage { + /** The server's CPU use with 100 per busy thread, or null when the JVM cannot tell. */ + cpuPercent: number | null + /** The threads the server's CPU has, so the CPU can reach 100 times this. */ + threads: number + heapUsedBytes: number + heapMaxBytes: number +} + /** * A decoded map tile. Grids hold (size + 2)² cells, the tile's pixels inside a ring of its neighbours' edge pixels. */ diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index aeb040f99..bab242e9e 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ThemeChoice } from '../../../shared/bridge' import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' -import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, ViewInfo, WorldInfo } from '../bridge/types' +import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, ServerUsage, ViewInfo, WorldInfo } from '../bridge/types' import type { Share } from '../map/census' import type { MapController, MapStatus, MapToggles } from '../map/MapController' import type { Highlight } from '../map/tileStyle' @@ -51,6 +51,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps const [shares, setShares] = useState([]) const [players, setPlayers] = useState([]) const [entities, setEntities] = useState([]) + const [usage, setUsage] = useState(null) const [pointer, setPointer] = useState(null) const [hover, setHover] = useState(null) const [detailed, setDetailed] = useState(false) @@ -103,7 +104,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps }, [players, toggles.follow]) const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), []) - useServerEvents(client, controller, setPlayers, tell, setConnected, packReloaded) + useServerEvents(client, controller, setPlayers, setUsage, tell, setConnected, packReloaded) useEntities(client, toggles.entities, setEntities) useHover(client, controller, layer, pointer, setHover) @@ -289,7 +290,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps )} - + ) @@ -412,11 +413,12 @@ function usePickInspection( return inspection } -/** Players and hotloads from the server; the first world event only says the world runs, which is known. */ +/** Players, usage and hotloads from the server; the first world event only says the world runs, which is known. */ function useServerEvents( client: BridgeClient, controller: React.RefObject, setPlayers: (players: Marker[]) => void, + setUsage: (usage: ServerUsage) => void, tell: (message: string) => void, setConnected: (connected: boolean) => void, onPackReloaded: () => void @@ -440,12 +442,13 @@ function useServerEvents( } }, onPlayers: setPlayers, + onUsage: setUsage, onClosed: () => setConnected(false) }, stop.signal ) return () => stop.abort() - }, [client, controller, setPlayers, tell, setConnected, onPackReloaded]) + }, [client, controller, setPlayers, setUsage, tell, setConnected, onPackReloaded]) } function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void { diff --git a/studio/src/renderer/src/studio/StatusBar.tsx b/studio/src/renderer/src/studio/StatusBar.tsx index 71596ceeb..6a63992cd 100644 --- a/studio/src/renderer/src/studio/StatusBar.tsx +++ b/studio/src/renderer/src/studio/StatusBar.tsx @@ -1,15 +1,21 @@ +import { MemoryStick, Zap } from 'lucide-react' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { cn } from '@/lib/utils' +import type { ServerUsage } from '../bridge/types' import type { MapStatus } from '../map/MapController' +import { cpuIsHigh, formatCpu, formatHeap, heapIsHigh } from './serverUsage' interface StatusBarProps { viewLabel: string status: MapStatus | null notice: string | null + usage: ServerUsage | null } const NUMBER = new Intl.NumberFormat('en-US') /** What the map shows, what it is busy with, and where the cursor is (v3e StudioStatusBar). */ -export function StatusBar({ viewLabel, status, notice }: StatusBarProps): React.JSX.Element { +export function StatusBar({ viewLabel, status, notice, usage }: StatusBarProps): React.JSX.Element { const drawing = status !== null && status.tilesReady < status.tilesTotal return (