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
This commit is contained in:
piexel committed 2026-11-10 11:31:27 +01:00
1 parent d28b9d13cc
commit 723764a782
10 files changed
+243 -8

No files matched your search

@@ -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 <https://www.gnu.org/licenses/>.
*/
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;
}
}
@@ -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<OutputStream> listeners = new CopyOnWriteArrayList<>();
private final AtomicBoolean listenerJoined = new AtomicBoolean();
private final AtomicBoolean usageWanted = new AtomicBoolean();
private final AtomicBoolean hotloaded = new AtomicBoolean();
private List<GuiMarker> 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);
}
}
@@ -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());
}
}
@@ -211,6 +211,24 @@ public class StudioBridgeTest {
}
}
@Test
public void aNewListenerHearsTheServersUsageRightAway() throws Exception {
HttpResponse<InputStream> 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<String> get(String endpoint) throws Exception {
return http.send(authorized(endpoint), HttpResponse.BodyHandlers.ofString());
}
@@ -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)
}
}
+10
View File
@@ -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.
*/
+8 -5
View File
@@ -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<Share[]>([])
const [players, setPlayers] = useState<Marker[]>([])
const [entities, setEntities] = useState<Marker[]>([])
const [usage, setUsage] = useState<ServerUsage | null>(null)
const [pointer, setPointer] = useState<CanvasPoint | null>(null)
const [hover, setHover] = useState<MapHover | null>(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
</>
)}
</div>
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} />
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} usage={usage} />
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={views} />
</div>
)
@@ -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<MapController | null>,
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 {
+44 -1
View File
@@ -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 (
<footer className="flex h-6 shrink-0 items-center gap-6 border-t bg-card px-3 text-[11.5px] text-secondary-text tabular-nums">
@@ -32,6 +38,7 @@ export function StatusBar({ viewLabel, status, notice }: StatusBarProps): React.
</span>
)}
</span>
{usage !== null && <UsageReadout usage={usage} />}
{status !== null && (
<span>
X {NUMBER.format(status.cursorX)}
@@ -42,6 +49,42 @@ export function StatusBar({ viewLabel, status, notice }: StatusBarProps): React.
)
}
/** The server's CPU, 100% per busy thread, and Java heap; each turns warning-coloured at 80%. */
function UsageReadout({ usage }: { usage: ServerUsage }): React.JSX.Element {
return (
<span className="flex items-center gap-4">
<Reading
icon={<Zap className="size-3.5" />}
value={formatCpu(usage)}
high={cpuIsHigh(usage)}
hint={`Server CPU, 100% per busy thread, ${usage.threads} threads in all`}
/>
<Reading icon={<MemoryStick className="size-3.5" />} value={formatHeap(usage)} high={heapIsHigh(usage)} hint="Java memory the server uses, of its maximum" />
</span>
)
}
interface ReadingProps {
icon: React.ReactNode
value: string
high: boolean
hint: string
}
function Reading({ icon, value, high, hint }: ReadingProps): React.JSX.Element {
return (
<Tooltip>
<TooltipTrigger asChild>
<span className={cn('flex items-center gap-1', high && 'text-warning')}>
{icon}
{value}
</span>
</TooltipTrigger>
<TooltipContent>{hint}</TooltipContent>
</Tooltip>
)
}
function Gap(): React.JSX.Element {
return <span className="inline-block w-3" />
}
@@ -0,0 +1,31 @@
import { describe, expect, it } from 'vitest'
import type { ServerUsage } from '../bridge/types'
import { cpuIsHigh, formatCpu, formatHeap, heapIsHigh } from './serverUsage'
const GIGABYTE = 1024 ** 3
function usageOf(cpuPercent: number | null, heapGigabytes: number): ServerUsage {
return { cpuPercent, threads: 8, heapUsedBytes: heapGigabytes * GIGABYTE, heapMaxBytes: 10 * GIGABYTE }
}
describe('server usage', () => {
it('shows the CPU in percent per busy thread, and a dash when the server cannot tell', () => {
expect(formatCpu(usageOf(312.4, 1))).toBe('312%')
expect(formatCpu(usageOf(null, 1))).toBe('–')
})
it('shows the heap in use of its maximum in gigabytes', () => {
expect(formatHeap(usageOf(0, 3.25))).toBe('3.3 / 10.0 GB')
})
it('warns once four fifths of the threads are busy, not before', () => {
expect(cpuIsHigh(usageOf(639, 1))).toBe(false)
expect(cpuIsHigh(usageOf(640, 1))).toBe(true)
expect(cpuIsHigh(usageOf(null, 1))).toBe(false)
})
it('warns once four fifths of the heap is in use, not before', () => {
expect(heapIsHigh(usageOf(0, 7.9))).toBe(false)
expect(heapIsHigh(usageOf(0, 8))).toBe(true)
})
})
@@ -0,0 +1,27 @@
import type { ServerUsage } from '../bridge/types'
const HIGH_USAGE = 0.8
const PERCENT_PER_THREAD = 100
const BYTES_PER_GIGABYTE = 1024 ** 3
export function formatCpu(usage: ServerUsage): string {
return usage.cpuPercent === null ? '–' : `${Math.round(usage.cpuPercent)}%`
}
export function formatHeap(usage: ServerUsage): string {
return `${gigabytes(usage.heapUsedBytes)} / ${gigabytes(usage.heapMaxBytes)} GB`
}
/** Whether four fifths of the CPU's threads are busy. */
export function cpuIsHigh(usage: ServerUsage): boolean {
return usage.cpuPercent !== null && usage.cpuPercent >= usage.threads * PERCENT_PER_THREAD * HIGH_USAGE
}
/** Whether four fifths of the heap is in use. */
export function heapIsHigh(usage: ServerUsage): boolean {
return usage.heapUsedBytes >= usage.heapMaxBytes * HIGH_USAGE
}
function gigabytes(bytes: number): string {
return (bytes / BYTES_PER_GIGABYTE).toFixed(1)
}