Report build and system facts on development builds

Printed at startup, by /iris debug info and in the debug dump
This commit is contained in:
piexel committed 2026-11-30 22:50:40 +01:00
1 parent 8893432b6f
commit 9413e2ff5f
24 files changed
+1166 -131

No files matched your search

@@ -0,0 +1,318 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.generation.simd.SimdSupport;
import art.arcane.iris.pack.PackValidationRegistry;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.platform.bukkit.nms.INMS;
import art.arcane.iris.platform.bukkit.nms.v1X.NMSBinding1X;
import art.arcane.iris.world.safeguard.IrisSafeguard;
import art.arcane.iris.world.safeguard.Mode;
import art.arcane.volmlib.util.noise.FractalBillowSimplexNoise;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.TreeMap;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/** The build block: which jar runs, what it was built against, and what startup made of it. */
public final class BuildFacts {
private static final String VOLMLIB_STAMP = "META-INF/volmit/volmlib.properties";
private static final String LOCAL_VOLMLIB_SOURCE = "local";
private static final int SHORT_COMMIT_LENGTH = 7;
private static final String DIRTY_MARK = "+dirty";
private static final String NATIVE_NOISE_STATUS_PREFIX = "native";
private static final String SCALAR_SIMD = "scalar";
private static final Pattern IRIS_JAR_NAME = Pattern.compile("(?i)iris\\b.*\\.jar");
private static final int SETTINGS_SHOWN = 4;
private static final int PACKS_SHOWN = 6;
private BuildFacts() {
}
enum TerrainProvider {
NATIVE,
DISABLED,
UNBOUND
}
enum PackOutcome {
LOADABLE,
WAITING,
FAILED
}
record Jar(String path, Optional<Duration> age, List<String> otherIrisJars) {
}
record Natives(String noiseStatus, TerrainProvider terrain, String simd) {
}
record PackState(String name, PackOutcome outcome, int warnings) {
}
public static DiagnosticSection current(Predicate<PackValidationResult> awaitingExternalContent) {
return DiagnosticSection.gather(title(BuildIdentity.current()), List.of(
() -> currentJar().flatMap(BuildFacts::jar),
() -> volmLibStamp().flatMap(BuildFacts::volmLib),
() -> natives(currentNatives()),
() -> settings(currentSettingChanges()),
() -> checks(IrisSafeguard.asContext()),
() -> packs(packStates(PackValidationRegistry.snapshot(), awaitingExternalContent))));
}
static String title(BuildIdentity build) {
if (!build.channel().isDevelopment()) {
return "Build " + build.commitLabel();
}
String title = "Dev build " + build.commitLabel();
return build.hasBranch() ? title + " on " + build.branch() : title;
}
static Optional<DiagnosticFact> jar(Jar jar) {
DiagnosticFact.Items items = new DiagnosticFact.Items().plain(jar.path());
jar.age().ifPresent(age -> items.muted("deployed " + FactFormat.age(age) + " ago"));
if (!jar.otherIrisJars().isEmpty()) {
items.warning("also " + String.join(", ", jar.otherIrisJars()));
}
return items.fact("Jar");
}
static Optional<DiagnosticFact> volmLib(Properties stamp) {
String source = stamp.getProperty("source");
if (source == null || source.isBlank()) {
return Optional.empty();
}
if (!LOCAL_VOLMLIB_SOURCE.equals(source)) {
return new DiagnosticFact.Items().plain(source).fact("VolmLib");
}
String commit = stamp.getProperty("commit", "unknown");
String shortCommit = commit.length() > SHORT_COMMIT_LENGTH ? commit.substring(0, SHORT_COMMIT_LENGTH) : commit;
String dirtyMark = Boolean.parseBoolean(stamp.getProperty("dirty")) ? DIRTY_MARK : "";
return new DiagnosticFact.Items().plain(LOCAL_VOLMLIB_SOURCE + " @ " + shortCommit + dirtyMark).fact("VolmLib");
}
static Optional<DiagnosticFact> natives(Natives natives) {
boolean nativeNoise = natives.noiseStatus().startsWith(NATIVE_NOISE_STATUS_PREFIX);
return new DiagnosticFact.Items()
.flagged(nativeNoise ? "noise ok" : "noise " + natives.noiseStatus(), !nativeNoise)
.flagged(terrainLabel(natives.terrain()), natives.terrain() != TerrainProvider.NATIVE)
.flagged("SIMD " + natives.simd(), SCALAR_SIMD.equals(natives.simd()))
.fact("Natives");
}
private static String terrainLabel(TerrainProvider terrain) {
return switch (terrain) {
case NATIVE -> "terrain ok";
case DISABLED -> "terrain off";
case UNBOUND -> "terrain failed";
};
}
static Optional<DiagnosticFact> settings(Map<String, String> changes) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (changes.isEmpty()) {
return items.muted("defaults").fact("Settings");
}
changes.entrySet().stream()
.limit(SETTINGS_SHOWN)
.forEach(change -> items.plain(change.getKey() + "=" + change.getValue()));
int hidden = changes.size() - SETTINGS_SHOWN;
if (hidden > 0) {
items.muted("+" + hidden + " more");
}
return items.fact("Settings");
}
/** Every leaf of {@code current} that differs from {@code defaults}, keyed by its dotted path, in settings order. */
static Map<String, String> settingChanges(JsonElement current, JsonElement defaults) {
Map<String, String> changes = new LinkedHashMap<>();
collectSettingChanges("", current, defaults, changes);
return changes;
}
private static void collectSettingChanges(String path, JsonElement current, JsonElement defaults,
Map<String, String> changes) {
if (current == null || !current.isJsonObject()) {
if (!Objects.equals(current, defaults)) {
changes.put(path, settingValue(current));
}
return;
}
JsonObject defaultSection = defaults != null && defaults.isJsonObject() ? defaults.getAsJsonObject() : new JsonObject();
for (Map.Entry<String, JsonElement> setting : current.getAsJsonObject().entrySet()) {
String settingPath = path.isEmpty() ? setting.getKey() : path + "." + setting.getKey();
collectSettingChanges(settingPath, setting.getValue(), defaultSection.get(setting.getKey()), changes);
}
}
private static String settingValue(JsonElement value) {
if (value == null || value.isJsonNull()) {
return "null";
}
return value.isJsonPrimitive() ? value.getAsString() : value.toString();
}
static Optional<DiagnosticFact> checks(Map<String, String> modeIdsByCheck) {
Map<Mode, List<String>> checksByMode = new EnumMap<>(Mode.class);
modeIdsByCheck.forEach((check, modeId) -> checksByMode
.computeIfAbsent(Mode.valueOf(modeId.toUpperCase(Locale.ROOT)), ignored -> new ArrayList<>())
.add(check));
DiagnosticFact.Items items = new DiagnosticFact.Items();
checksByMode.forEach((mode, checks) -> {
if (mode == Mode.STABLE) {
items.plain(checks.size() + " ok");
return;
}
String outcome = mode == Mode.WARNING ? " warn (" : " failed (";
items.warning(checks.size() + outcome + String.join(", ", checks) + ")");
});
return items.fact("Checks");
}
static Optional<DiagnosticFact> packs(List<PackState> packs) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (packs.isEmpty()) {
return items.muted("none").fact("Packs");
}
packs.stream().limit(PACKS_SHOWN).forEach(pack -> addPack(items, pack));
int hidden = packs.size() - PACKS_SHOWN;
if (hidden > 0) {
items.muted("+" + hidden + " more");
}
return items.fact("Packs");
}
private static void addPack(DiagnosticFact.Items items, PackState pack) {
switch (pack.outcome()) {
case FAILED -> items.warning(pack.name() + " failed");
case WAITING -> items.muted(pack.name() + " waiting");
case LOADABLE -> {
if (pack.warnings() == 0) {
items.plain(pack.name() + " ok");
return;
}
items.warning(pack.name() + " " + pack.warnings() + (pack.warnings() == 1 ? " warning" : " warnings"));
}
}
}
static List<PackState> packStates(Map<String, PackValidationResult> resultsByPack,
Predicate<PackValidationResult> awaitingExternalContent) {
List<PackState> states = new ArrayList<>(resultsByPack.size());
new TreeMap<>(resultsByPack).forEach((pack, result) -> states.add(new PackState(pack,
packOutcome(result, awaitingExternalContent), result.getWarnings().size())));
return states;
}
private static PackOutcome packOutcome(PackValidationResult result, Predicate<PackValidationResult> awaitingExternalContent) {
if (result.isLoadable()) {
return PackOutcome.LOADABLE;
}
return awaitingExternalContent.test(result) ? PackOutcome.WAITING : PackOutcome.FAILED;
}
private static Optional<Jar> currentJar() {
Optional<Path> runningJar = runningJar();
if (runningJar.isEmpty()) {
return Optional.empty();
}
Path jar = runningJar.get();
return Optional.of(new Jar(serverRelative(jar), modificationAge(jar), otherIrisJars(jar)));
}
private static Optional<Path> runningJar() {
try {
CodeSource source = BuildFacts.class.getProtectionDomain().getCodeSource();
if (source == null || source.getLocation() == null) {
return Optional.empty();
}
Path jar = Path.of(source.getLocation().toURI()).toAbsolutePath().normalize();
return Files.isRegularFile(jar) ? Optional.of(jar) : Optional.empty();
} catch (URISyntaxException unresolvable) {
return Optional.empty();
}
}
/** The server runs from its root folder, so the working directory is what paths are relative to. */
private static String serverRelative(Path jar) {
Path serverRoot = Path.of("").toAbsolutePath().normalize();
Path shown = jar.startsWith(serverRoot) ? serverRoot.relativize(jar) : jar;
return shown.toString().replace('\\', '/');
}
/** A plain copy resets the modification time, so this is when the jar was deployed rather than built. */
private static Optional<Duration> modificationAge(Path jar) {
try {
Instant modified = Files.getLastModifiedTime(jar).toInstant();
return Optional.of(Duration.between(modified, Instant.now()));
} catch (IOException unreadable) {
return Optional.empty();
}
}
private static List<String> otherIrisJars(Path jar) {
Path folder = jar.getParent();
if (folder == null) {
return List.of();
}
try (Stream<Path> files = Files.list(folder)) {
return files.filter(file -> !file.equals(jar) && Files.isRegularFile(file))
.map(file -> file.getFileName().toString())
.filter(name -> IRIS_JAR_NAME.matcher(name).matches())
.sorted()
.toList();
} catch (IOException unreadable) {
return List.of();
}
}
private static Optional<Properties> volmLibStamp() {
try (InputStream input = BuildFacts.class.getClassLoader().getResourceAsStream(VOLMLIB_STAMP)) {
if (input == null) {
return Optional.empty();
}
Properties stamp = new Properties();
stamp.load(input);
return Optional.of(stamp);
} catch (IOException unreadable) {
return Optional.empty();
}
}
private static Natives currentNatives() {
return new Natives(FractalBillowSimplexNoise.nativeBackendStatus(), currentTerrainProvider(), SimdSupport.shortStatus());
}
private static TerrainProvider currentTerrainProvider() {
if (!INMS.isBound()) {
return TerrainProvider.UNBOUND;
}
return INMS.get() instanceof NMSBinding1X ? TerrainProvider.DISABLED : TerrainProvider.NATIVE;
}
private static Map<String, String> currentSettingChanges() {
Gson gson = new Gson();
return settingChanges(gson.toJsonTree(IrisSettings.get()), gson.toJsonTree(new IrisSettings()));
}
}
@@ -0,0 +1,27 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.BuildConstants;
/** Which source a jar was built from, as the splash and the build report name it. */
public record BuildIdentity(BuildChannel channel, String commit, String environment, String branch, boolean dirty) {
private static final int SHORT_COMMIT_LENGTH = 7;
private static final String DIRTY_MARK = "+dirty";
public static BuildIdentity current() {
return new BuildIdentity(BuildChannel.current(), BuildConstants.COMMIT, BuildConstants.ENVIRONMENT,
BuildConstants.BRANCH, BuildConstants.DIRTY);
}
/** "df31f1e/production" on a release; on a development build the environment gives way to the dirty mark. */
public String commitLabel() {
String shortCommit = commit.length() > SHORT_COMMIT_LENGTH ? commit.substring(0, SHORT_COMMIT_LENGTH) : commit;
if (!channel.isDevelopment()) {
return shortCommit + "/" + environment;
}
return dirty ? shortCommit + DIRTY_MARK : shortCommit;
}
public boolean hasBranch() {
return branch != null && !branch.isBlank();
}
}
@@ -0,0 +1,54 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.ChatReport.ValuePart;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/** One labelled line of a diagnostics section, such as "Jar" or "Memory". */
public record DiagnosticFact(String label, List<ValuePart> value) {
public DiagnosticFact {
value = List.copyOf(value);
}
public String plainValue() {
return value.stream().map(ValuePart::text).collect(Collectors.joining());
}
/** A fact's value as a comma separated list; the separators stay muted so the items carry the color. */
static final class Items {
private static final String SEPARATOR = ", ";
private final List<ValuePart> parts = new ArrayList<>();
Items plain(String text) {
return add(ValuePart.plain(text));
}
Items muted(String text) {
return add(ValuePart.muted(text));
}
Items warning(String text) {
return add(ValuePart.warning(text));
}
Items flagged(String text, boolean needsLook) {
return needsLook ? warning(text) : plain(text);
}
Optional<DiagnosticFact> fact(String label) {
return parts.isEmpty() ? Optional.empty() : Optional.of(new DiagnosticFact(label, parts));
}
private Items add(ValuePart part) {
if (!parts.isEmpty()) {
parts.add(ValuePart.muted(SEPARATOR));
}
parts.add(part);
return this;
}
}
}
@@ -0,0 +1,45 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.spi.IrisLogging;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
/** A titled block of facts, printed as a console or chat report or written as plain text into the debug dump. */
public record DiagnosticSection(String title, List<DiagnosticFact> facts) {
private static final String PLAIN_INDENT = " ";
public DiagnosticSection {
facts = List.copyOf(facts);
}
/** Gathers each fact on its own, so a fact that cannot be determined is left out instead of failing the section. */
static DiagnosticSection gather(String title, List<Supplier<Optional<DiagnosticFact>>> gatherers) {
List<DiagnosticFact> facts = new ArrayList<>(gatherers.size());
for (Supplier<Optional<DiagnosticFact>> gatherer : gatherers) {
try {
gatherer.get().ifPresent(facts::add);
} catch (RuntimeException | LinkageError undeterminable) {
IrisLogging.debug("Diagnostics left out a fact of '" + title + "': " + undeterminable);
}
}
return new DiagnosticSection(title, facts);
}
public ChatReport report() {
ChatReport.Builder report = ChatReport.of(ChatReport.Tone.DIAGNOSTIC, title).unlimited();
facts.forEach(fact -> report.entry(fact.label(), fact.value()));
return report.build();
}
public String plainText() {
StringBuilder text = new StringBuilder(title);
for (DiagnosticFact fact : facts) {
text.append('\n').append(PLAIN_INDENT).append(fact.label()).append(": ").append(fact.plainValue());
}
return text.toString();
}
}
@@ -0,0 +1,23 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.pack.PackValidationResult;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** The build and system blocks, gathered fresh for each reader: the startup print, the command and the debug dump. */
public final class DiagnosticsReport {
private DiagnosticsReport() {
}
public static List<DiagnosticSection> sections(Predicate<PackValidationResult> awaitingExternalContent) {
return List.of(BuildFacts.current(awaitingExternalContent), SystemFacts.current());
}
public static String plainText(Predicate<PackValidationResult> awaitingExternalContent) {
return sections(awaitingExternalContent).stream()
.map(DiagnosticSection::plainText)
.collect(Collectors.joining("\n"));
}
}
@@ -0,0 +1,36 @@
package art.arcane.iris.diagnostics;
import java.time.Duration;
/** The compact units diagnostics print: ages like "36s" or "3d", sizes like "6G" or "512M". */
final class FactFormat {
private static final long SECONDS_PER_MINUTE = 60;
private static final long SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;
private static final long SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
private static final double BYTES_PER_GIB = 1L << 30;
private static final double BYTES_PER_MIB = 1L << 20;
private FactFormat() {
}
static String age(Duration age) {
long seconds = Math.max(0, age.toSeconds());
if (seconds < SECONDS_PER_MINUTE) {
return seconds + "s";
}
if (seconds < SECONDS_PER_HOUR) {
return seconds / SECONDS_PER_MINUTE + "m";
}
if (seconds < SECONDS_PER_DAY) {
return seconds / SECONDS_PER_HOUR + "h";
}
return seconds / SECONDS_PER_DAY + "d";
}
static String size(long bytes) {
if (bytes >= BYTES_PER_GIB) {
return Math.round(bytes / BYTES_PER_GIB) + "G";
}
return Math.round(Math.max(0, bytes) / BYTES_PER_MIB) + "M";
}
}
@@ -0,0 +1,219 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.platform.agent.Agent;
import art.arcane.iris.world.IrisWorldStorage;
import art.arcane.iris.world.pregen.AsyncPregenMethod;
import java.io.IOException;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** The system block: what the host gives this JVM and what Iris made of it. */
public final class SystemFacts {
private static final String TITLE = "System";
private static final Path CPU_INFO = Path.of("/proc/cpuinfo");
private static final Path MEMORY_INFO = Path.of("/proc/meminfo");
private static final List<Path> CONTAINER_MARKERS = List.of(
Path.of("/.dockerenv"), Path.of("/run/.containerenv"), Path.of("/run/systemd/container"));
private static final String CPU_THREAD_ENTRY = "processor";
private static final String CPU_MODEL_ENTRY = "model name";
private static final String AVAILABLE_MEMORY_ENTRY = "MemAvailable:";
private static final long BYTES_PER_KIB = 1024;
private static final String PRE_TOUCH_FLAG = "-XX:+AlwaysPreTouch";
private static final Pattern MAJOR_MINOR_VERSION = Pattern.compile("^(\\d+\\.\\d+)");
private static final List<Pattern> CPU_MODEL_NOISE = List.of(
Pattern.compile("\\((?:R|TM|tm)\\)"),
Pattern.compile("\\s*@.*$"),
Pattern.compile("\\s+\\d+-Core Processor$"),
Pattern.compile("\\s+(?:CPU|Processor)\\b"),
Pattern.compile("^(?:AMD|Intel)\\s+"));
private SystemFacts() {
}
record Cpu(int availableThreads, OptionalInt hostThreads, Optional<String> model) {
}
record Pools(int generation, int io, int pregen) {
}
record Memory(long maxHeapBytes, OptionalLong hostBytes, OptionalLong hostAvailableBytes) {
}
record Jvm(int feature, Optional<String> collector, boolean preTouch, boolean agentAttached) {
}
record Os(String name, String version, String architecture, boolean container) {
}
public static DiagnosticSection current() {
return DiagnosticSection.gather(TITLE, List.of(
() -> cpu(currentCpu()),
() -> pools(currentPools()),
() -> memory(currentMemory()),
() -> jvm(currentJvm()),
() -> os(currentOs()),
() -> disk(IrisWorldStorage.levelRoot().getFreeSpace())));
}
static Optional<DiagnosticFact> cpu(Cpu cpu) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
if (cpu.hostThreads().isEmpty()) {
items.plain(cpu.availableThreads() + " threads available");
cpu.model().ifPresent(items::muted);
return items.fact("CPU");
}
int hostThreads = cpu.hostThreads().getAsInt();
boolean limited = cpu.availableThreads() < hostThreads;
items.flagged(cpu.availableThreads() + " of " + hostThreads + " threads available", limited);
cpu.model().ifPresent(items::muted);
if (limited) {
items.warning("limited");
} else {
items.muted("no limit");
}
return items.fact("CPU");
}
static Optional<DiagnosticFact> pools(Pools pools) {
DiagnosticFact.Items items = new DiagnosticFact.Items();
addPool(items, "generation", pools.generation());
addPool(items, "io", pools.io());
addPool(items, "pregen", pools.pregen());
return items.fact("Iris pools");
}
private static void addPool(DiagnosticFact.Items items, String pool, int workers) {
if (workers > 0) {
items.plain(pool + " " + workers);
}
}
static Optional<DiagnosticFact> memory(Memory memory) {
String heap = "heap " + FactFormat.size(memory.maxHeapBytes());
DiagnosticFact.Items items = new DiagnosticFact.Items();
memory.hostBytes().ifPresentOrElse(
host -> items.plain(heap + " of " + FactFormat.size(host) + " host"),
() -> items.plain(heap));
memory.hostAvailableBytes().ifPresent(available -> items.muted(FactFormat.size(available) + " available"));
return items.fact("Memory");
}
static Optional<DiagnosticFact> jvm(Jvm jvm) {
DiagnosticFact.Items items = new DiagnosticFact.Items().plain("Java " + jvm.feature());
jvm.collector().ifPresent(items::plain);
if (jvm.preTouch()) {
items.muted("pretouch");
}
items.muted(jvm.agentAttached() ? "agent attached" : "no agent");
return items.fact("JVM");
}
static Optional<DiagnosticFact> os(Os os) {
Matcher majorMinor = MAJOR_MINOR_VERSION.matcher(os.version());
String version = majorMinor.find() ? majorMinor.group(1) : os.version();
DiagnosticFact.Items items = new DiagnosticFact.Items()
.plain(os.name() + " " + version)
.muted(os.architecture());
if (os.container()) {
items.muted("container");
}
return items.fact("OS");
}
static Optional<DiagnosticFact> disk(long worldFreeBytes) {
return new DiagnosticFact.Items().plain("world folder " + FactFormat.size(worldFreeBytes) + " free").fact("Disk");
}
/** Drops trademarks, vendor, clock and core count, so "AMD Ryzen 9 7950X 16-Core Processor" reads "Ryzen 9 7950X". */
static String compactCpuModel(String model) {
String compact = model.strip();
for (Pattern noise : CPU_MODEL_NOISE) {
compact = noise.matcher(compact).replaceAll("");
}
return compact.replaceAll("\\s+", " ").strip();
}
private static Cpu currentCpu() {
int availableThreads = Runtime.getRuntime().availableProcessors();
List<String> cpuInfo = readLines(CPU_INFO);
long hostThreads = cpuInfo.stream().filter(line -> line.startsWith(CPU_THREAD_ENTRY)).count();
Optional<String> model = cpuInfo.stream()
.filter(line -> line.startsWith(CPU_MODEL_ENTRY))
.findFirst()
.map(line -> compactCpuModel(line.substring(line.indexOf(':') + 1)));
return new Cpu(availableThreads, hostThreads > 0 ? OptionalInt.of((int) hostThreads) : OptionalInt.empty(), model);
}
private static Pools currentPools() {
return new Pools(MultiBurst.burst.parallelism(), MultiBurst.ioBurst.parallelism(),
AsyncPregenMethod.plannedWorkerThreads());
}
private static Memory currentMemory() {
long maxHeap = Runtime.getRuntime().maxMemory();
OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
if (!(system instanceof com.sun.management.OperatingSystemMXBean host)) {
return new Memory(maxHeap, OptionalLong.empty(), OptionalLong.empty());
}
OptionalLong available = availableMemory();
return new Memory(maxHeap, OptionalLong.of(host.getTotalMemorySize()),
available.isPresent() ? available : OptionalLong.of(host.getFreeMemorySize()));
}
/** Linux counts page cache as used in its free figure, so the reclaimable estimate says more about headroom. */
private static OptionalLong availableMemory() {
return readLines(MEMORY_INFO).stream()
.filter(line -> line.startsWith(AVAILABLE_MEMORY_ENTRY))
.findFirst()
.map(line -> line.substring(AVAILABLE_MEMORY_ENTRY.length()).replace("kB", "").strip())
.map(kibibytes -> OptionalLong.of(Long.parseLong(kibibytes) * BYTES_PER_KIB))
.orElse(OptionalLong.empty());
}
private static Jvm currentJvm() {
Optional<String> collector = ManagementFactory.getGarbageCollectorMXBeans().stream()
.findFirst()
.map(GarbageCollectorMXBean::getName)
.map(SystemFacts::collectorName);
boolean preTouch = ManagementFactory.getRuntimeMXBean().getInputArguments().contains(PRE_TOUCH_FLAG);
return new Jvm(Runtime.version().feature(), collector, preTouch, Agent.isInstalled());
}
/** Collector beans are named per generation, like "G1 Young Generation" or "PS Scavenge". */
static String collectorName(String beanName) {
String family = beanName.split(" ", 2)[0];
return switch (family) {
case "PS" -> "Parallel";
case "Copy", "MarkSweepCompact" -> "Serial";
default -> family;
};
}
private static Os currentOs() {
boolean container = CONTAINER_MARKERS.stream().anyMatch(Files::exists);
return new Os(System.getProperty("os.name", "unknown"), System.getProperty("os.version", ""),
System.getProperty("os.arch", "unknown"), container);
}
private static List<String> readLines(Path file) {
if (!Files.isReadable(file)) {
return List.of();
}
try {
return Files.readAllLines(file);
} catch (IOException unreadable) {
return List.of();
}
}
}
@@ -1,9 +1,9 @@
package art.arcane.iris.diagnostics.splash;
import art.arcane.iris.diagnostics.BuildIdentity;
import art.arcane.iris.localization.ChatReport;
import art.arcane.iris.pack.BuiltInPackUpdates;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -17,14 +17,10 @@ public final class IrisSplashComposer {
private static final int FIRST_SPARE_INFO_ROW = 7;
private static final int SPARE_INFO_ROWS = 3;
private static final int PACKS_SHOWN = 6;
private static final int SHORT_COMMIT_LENGTH = 7;
private static final int LABEL_WIDTH = 14;
private static final String FACT_GAP = " ";
private static final String DEVELOPMENT_TAG_SUFFIX = " DEV";
private static final String DIRTY_MARK = "+dirty";
private static final long SECONDS_PER_MINUTE = 60;
private static final long SECONDS_PER_HOUR = 60 * SECONDS_PER_MINUTE;
private static final long SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR;
private static final String DEVELOPMENT_VERSION_SUFFIX = " (dev)";
private IrisSplashComposer() {
}
@@ -34,10 +30,10 @@ public final class IrisSplashComposer {
}
public static String[] composeInfo(String version, String serverLine, InfoStyle style, List<List<Detail>> detailRows) {
return composeInfo(version, serverLine, style, SplashBuild.current(), detailRows);
return composeInfo(version, serverLine, style, BuildIdentity.current(), detailRows);
}
public static String[] composeInfo(String version, String serverLine, InfoStyle style, SplashBuild build,
public static String[] composeInfo(String version, String serverLine, InfoStyle style, BuildIdentity build,
List<List<Detail>> detailRows) {
String[] info = composeHeader(version, serverLine, style, build);
int rows = Math.min(detailRows.size(), SPARE_INFO_ROWS);
@@ -80,21 +76,17 @@ public final class IrisSplashComposer {
return text + " ".repeat(Math.max(1, width - text.length()));
}
private static String shortCommit(String commit) {
return commit.length() > SHORT_COMMIT_LENGTH ? commit.substring(0, SHORT_COMMIT_LENGTH) : commit;
}
private static String[] composeHeader(String version, String serverLine, InfoStyle style, SplashBuild build) {
private static String[] composeHeader(String version, String serverLine, InfoStyle style, BuildIdentity build) {
String prefix = style.linePrefix();
String java = javaVersion() < 0 ? "unknown" : String.valueOf(javaVersion());
return new String[]{
prefix + style.title(" Iris, ") + style.subtitle("Dimension Engine ") + style.tag("[" + titleTag(version, build) + "]"),
prefix + styledRow(List.of(Detail.headline("Version", version)), style),
prefix + styledRow(List.of(Detail.headline("Version", versionLabel(version, build))), style),
prefix + styledRow(List.of(new Detail("By", "Volmit Software (Arcane Arts)")), style),
prefix + styledRow(List.of(new Detail("Web", "volmitsoftware.com")), style),
prefix + styledRow(List.of(Detail.headline("Server", serverLine)), style),
prefix + styledRow(List.of(new Detail("Java", java), new Detail("Date", startupDate())), style),
prefix + styledRow(buildFacts(build), style),
prefix + styledRow(List.of(new Detail("Commit", build.commitLabel())), style),
"",
"",
"",
@@ -102,37 +94,13 @@ public final class IrisSplashComposer {
};
}
private static String titleTag(String version, SplashBuild build) {
private static String titleTag(String version, BuildIdentity build) {
String releaseTrain = releaseTrain(version);
return build.channel().isDevelopment() ? releaseTrain + DEVELOPMENT_TAG_SUFFIX : releaseTrain;
}
private static List<Detail> buildFacts(SplashBuild build) {
String commit = shortCommit(build.commit());
if (!build.channel().isDevelopment()) {
return List.of(new Detail("Commit", commit + "/" + build.environment()));
}
List<Detail> facts = new ArrayList<>();
facts.add(new Detail("Commit", build.dirty() ? commit + DIRTY_MARK : commit));
if (build.hasBranch()) {
facts.add(new Detail("Branch", build.branch()));
}
build.age().ifPresent(age -> facts.add(new Detail("Built", compactAge(age) + " ago")));
return facts;
}
static String compactAge(Duration age) {
long seconds = Math.max(0, age.toSeconds());
if (seconds < SECONDS_PER_MINUTE) {
return seconds + "s";
}
if (seconds < SECONDS_PER_HOUR) {
return seconds / SECONDS_PER_MINUTE + "m";
}
if (seconds < SECONDS_PER_DAY) {
return seconds / SECONDS_PER_HOUR + "h";
}
return seconds / SECONDS_PER_DAY + "d";
private static String versionLabel(String version, BuildIdentity build) {
return build.channel().isDevelopment() ? version + DEVELOPMENT_VERSION_SUFFIX : version;
}
public static String compose(String[] splash, String[] info) {
@@ -1,44 +0,0 @@
package art.arcane.iris.diagnostics.splash;
import art.arcane.iris.BuildConstants;
import art.arcane.iris.diagnostics.BuildChannel;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.CodeSource;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
/** What the splash says about the build it is running from. */
public record SplashBuild(BuildChannel channel, String commit, String environment, String branch, boolean dirty,
Optional<Duration> age) {
public static SplashBuild current() {
return new SplashBuild(BuildChannel.current(), BuildConstants.COMMIT, BuildConstants.ENVIRONMENT,
BuildConstants.BRANCH, BuildConstants.DIRTY, jarAge());
}
public boolean hasBranch() {
return branch != null && !branch.isBlank();
}
/** The jar's modification time stands in for the build time, so no timestamp has to be compiled in. */
private static Optional<Duration> jarAge() {
try {
CodeSource source = SplashBuild.class.getProtectionDomain().getCodeSource();
URL location = source == null ? null : source.getLocation();
if (location == null) {
return Optional.empty();
}
Path jar = Path.of(location.toURI());
if (!Files.isRegularFile(jar)) {
return Optional.empty();
}
Instant built = Files.getLastModifiedTime(jar).toInstant();
return Optional.of(Duration.between(built, Instant.now()));
} catch (Exception unresolvable) {
return Optional.empty();
}
}
}
@@ -24,7 +24,9 @@ public final class ChatReport {
SUCCESS(C.IRIS, C.DARK_GREEN, ConsoleGlyphs.CHECK),
INFO(C.AQUA, C.AQUA, ""),
WARNING(C.GOLD, C.GOLD, ConsoleGlyphs.WARNING),
ERROR(C.RED, C.RED, ConsoleGlyphs.CROSS);
ERROR(C.RED, C.RED, ConsoleGlyphs.CROSS),
/** Build and system facts wear the purple of the development splash fins. */
DIAGNOSTIC(C.LIGHT_PURPLE, C.LIGHT_PURPLE, ConsoleGlyphs.DIAMOND);
private final C color;
private final C consoleColor;
@@ -69,6 +71,37 @@ public final class ChatReport {
}
}
/** How much a part of an entry's value asks to be read: the fact itself, an aside, or something to look at. */
public enum Emphasis {
PLAIN,
MUTED,
WARNING
}
public record ValuePart(String text, Emphasis emphasis) {
public static ValuePart plain(String text) {
return new ValuePart(text, Emphasis.PLAIN);
}
public static ValuePart muted(String text) {
return new ValuePart(text, Emphasis.MUTED);
}
public static ValuePart warning(String text) {
return new ValuePart(text, Emphasis.WARNING);
}
/** Plain parts keep the value color of their layout: Iris in chat, white on the console. */
private String styled(C plainColor) {
C color = switch (emphasis) {
case PLAIN -> plainColor;
case MUTED -> C.GRAY;
case WARNING -> Tone.WARNING.consoleColor();
};
return color + cleanInline(text);
}
}
/** A blank chat line. A single space, because some clients drop fully empty messages. */
public static final Line SPACER = new Line(" ", null);
@@ -83,13 +116,24 @@ public final class ChatReport {
}
/** One report entry. Chat shows its styled lines; the console draws them as a branch, a labelled entry as an aligned label row. */
private record Entry(List<String> styledLines, String label, String value) {
private record Entry(List<String> styledLines, String label, String consoleValue) {
static Entry styled(List<String> styledLines) {
return new Entry(List.copyOf(styledLines), null, null);
}
static Entry labelled(String label, String value) {
return new Entry(List.of(ChatReport.label(label, value)), clean(label), clean(value));
return new Entry(List.of(ChatReport.label(label, value)), clean(label), C.WHITE + clean(value));
}
static Entry labelled(String label, List<ValuePart> value) {
String chatLine = C.GRAY + clean(label) + C.DARK_GRAY + ": " + styledParts(value, C.IRIS);
return new Entry(List.of(chatLine), clean(label), styledParts(value, C.WHITE));
}
private static String styledParts(List<ValuePart> value, C plainColor) {
StringBuilder styled = new StringBuilder();
value.forEach(part -> styled.append(part.styled(plainColor)));
return styled.toString();
}
/** The branch's lines from column 2 on: the first sits on the branch, the rest on the trunk. */
@@ -109,9 +153,9 @@ public final class ChatReport {
private List<String> labelRow() {
if (label.length() < CONSOLE_LABEL_WIDTH) {
String padding = " ".repeat(CONSOLE_LABEL_WIDTH - label.length());
return List.of(C.GRAY + label + padding + C.WHITE + value);
return List.of(C.GRAY + label + padding + consoleValue);
}
return List.of(C.GRAY + label, " ".repeat(CONSOLE_LABEL_WIDTH) + C.WHITE + value);
return List.of(C.GRAY + label, " ".repeat(CONSOLE_LABEL_WIDTH) + consoleValue);
}
}
@@ -140,13 +184,17 @@ public final class ChatReport {
}
public static String clean(String text) {
return cleanInline(text).strip();
}
/** Like {@link #clean(String)}, but keeps the surrounding spaces a value part needs to join its neighbours. */
private static String cleanInline(String text) {
if (text == null) {
return "";
}
return LEGACY_COLOR.matcher(text).replaceAll("")
.replace("<", "‹")
.replace(">", "›")
.strip();
.replace(">", "›");
}
public static String label(String label, String value) {
@@ -344,6 +392,12 @@ public final class ChatReport {
return this;
}
/** A labelled entry whose value parts each keep their own emphasis. */
public Builder entry(String label, List<ValuePart> value) {
entries.add(Entry.labelled(label, List.copyOf(value)));
return this;
}
public Builder limit(int maxItems) {
this.itemLimit = Math.max(0, maxItems);
return this;
@@ -13,6 +13,7 @@ public final class ConsoleGlyphs {
public static final String CHECK = "\u2714";
public static final String WARNING = "\u25b2";
public static final String CROSS = "\u2716";
public static final String DIAMOND = "\u25c6";
public static final String ELLIPSIS = "\u2026";
private static final Map<String, String> ASCII_FALLBACKS = asciiFallbacks();
@@ -59,6 +60,7 @@ public final class ConsoleGlyphs {
fallbacks.put(CHECK, "+");
fallbacks.put(WARNING, "!");
fallbacks.put(CROSS, "x");
fallbacks.put(DIAMOND, "*");
fallbacks.put(ELLIPSIS, "...");
fallbacks.put("\u2039", "[");
fallbacks.put("\u203a", "]");
@@ -9,6 +9,7 @@ public final class DirectorCommandMessages {
public static final TextKey DEBUG_DESCRIPTION = TextKey.of("iris.director.commanddebug.description", "Iris diagnostic tools");
public static final TextKey DEBUG_DUMP_DESCRIPTION = TextKey.of("iris.director.commandiris.director.debugdump", "Create and optionally upload a diagnostic report");
public static final TextKey DEBUG_DUMP_UPLOAD = TextKey.of("iris.director.commandiris.param.debugdump_upload", "Upload the report to mclo.gs");
public static final TextKey DEBUG_INFO_DESCRIPTION = TextKey.of("iris.director.commanddebug.director.info", "Print build and system facts");
public static final TextKey COMMAND_DATAPACK_DIRECTOR_DOWNLOAD_MANAGE_EXTERNAL_DATAPACK_IMPORTS_MODRINTH = TextKey.of(
"iris.director.commanddatapack.director.download_manage_external_datapack_imports_modrinth",
"Download & manage external datapack imports"
@@ -950,6 +951,7 @@ public final class DirectorCommandMessages {
DEBUG_DESCRIPTION,
DEBUG_DUMP_DESCRIPTION,
DEBUG_DUMP_UPLOAD,
DEBUG_INFO_DESCRIPTION,
COMMAND_DATAPACK_DIRECTOR_DOWNLOAD_MANAGE_EXTERNAL_DATAPACK_IMPORTS_MODRINTH,
COMMAND_DATAPACK_DIRECTOR_DOWNLOAD_UPDATE_EVERY_DATAPACK_LISTED_PACK_DIMENSION_S_DATAPACKIMPORTS_INSTALL_IT_INTO,
COMMAND_DATAPACK_PARAM_RESTART_SERVER_WHEN_NEW_DATAPACKS_ARE_INSTALLED_REQUIRED_NEW_STRUCTURES_REGISTER_GENERATE,
@@ -139,8 +139,7 @@ public class AsyncPregenMethod implements PregeneratorMethod {
this.chunkAccessMode = chunkAsyncMethodSelection.mode();
int detectedWorkerPoolThreads = resolveWorkerPoolThreads();
int detectedCpuThreads = Math.max(1, Runtime.getRuntime().availableProcessors());
this.pregenWorkerThreads = pregenWorkerThreadTarget(detectedCpuThreads, MantleHeapPressure.memoryBudgetBytes(),
!foliaRuntime && !strictSerial && detectedWorkerPoolThreads > 0);
this.pregenWorkerThreads = workerThreadTarget(!foliaRuntime && !strictSerial && detectedWorkerPoolThreads > 0);
int workerThreadsForCap = foliaRuntime
? resolveFoliaConcurrencyWorkerThreads(detectedWorkerPoolThreads, detectedCpuThreads, pregenWorkerThreads)
: resolvePaperLikeConcurrencyWorkerThreads(detectedWorkerPoolThreads, detectedCpuThreads, pregenWorkerThreads);
@@ -650,6 +649,17 @@ public class AsyncPregenMethod implements PregeneratorMethod {
return Math.min(Math.max(1, concurrencyCap), Math.max(1, current) + 1);
}
/** The chunk worker count a pregeneration on this server raises the pool to, known before any run starts. */
public static int plannedWorkerThreads() {
boolean foliaRuntime = IrisRuntimeSchedulerMode.resolve(IrisSettings.get().getPregen()) == IrisRuntimeSchedulerMode.FOLIA;
return workerThreadTarget(!foliaRuntime);
}
private static int workerThreadTarget(boolean expanded) {
return pregenWorkerThreadTarget(Math.max(1, Runtime.getRuntime().availableProcessors()),
MantleHeapPressure.memoryBudgetBytes(), expanded);
}
static int pregenWorkerThreadTarget(int availableProcessors, long maximumHeapBytes, boolean expanded) {
int baseline = Math.max(2, availableProcessors);
if (!expanded || maximumHeapBytes < (16L << 30)) {
@@ -1,6 +1,5 @@
package art.arcane.iris.world.safeguard;
import art.arcane.iris.diagnostics.BuildChannel;
import art.arcane.iris.diagnostics.splash.IrisSplashComposer;
import art.arcane.iris.diagnostics.splash.IrisSplashRenderer;
import art.arcane.iris.platform.bukkit.BukkitPlatform;
@@ -16,11 +15,6 @@ public enum Mode {
WARNING(C.GOLD, C.YELLOW),
UNSTABLE(C.RED, C.GOLD);
private static final C RELEASE_FIN_SHADE = C.DARK_GRAY;
private static final C RELEASE_FIN_HIGHLIGHT = C.GRAY;
private static final C DEVELOPMENT_FIN_SHADE = C.DARK_PURPLE;
private static final C DEVELOPMENT_FIN_HIGHLIGHT = C.LIGHT_PURPLE;
private final C color;
private final C glow;
private final String id;
@@ -100,13 +94,12 @@ public enum Mode {
}
private String splashTone(char glyph) {
boolean development = BuildChannel.current().isDevelopment();
return switch (glyph) {
case '=' -> C.GRAY.toString();
case '*' -> glow.toString();
case '%', '@' -> color.toString();
case '(', ')' -> C.WHITE.toString();
case '=' -> (development ? DEVELOPMENT_FIN_HIGHLIGHT : RELEASE_FIN_HIGHLIGHT).toString();
default -> (development ? DEVELOPMENT_FIN_SHADE : RELEASE_FIN_SHADE).toString();
default -> C.DARK_GRAY.toString();
};
}
@@ -0,0 +1,149 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.localization.ChatReport.Emphasis;
import art.arcane.iris.localization.ChatReport.ValuePart;
import art.arcane.iris.pack.PackValidationResult;
import com.google.gson.Gson;
import org.junit.Test;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BuildFactsTest {
private static final String COMMIT = "df31f1e2e5f1c0a8d4b7e9f6a3c2b1d0e9f8a7b6";
private static boolean flagged(DiagnosticFact fact, String text) {
return fact.value().contains(ValuePart.warning(text));
}
private static boolean anyFlagged(DiagnosticFact fact) {
return fact.value().stream().anyMatch(part -> part.emphasis() == Emphasis.WARNING);
}
@Test
public void developmentTitleNamesCommitDirtyMarkAndBranch() {
assertEquals("Dev build df31f1e+dirty on t3/qol-changes", BuildFacts.title(
new BuildIdentity(BuildChannel.DEVELOPMENT, COMMIT, "development", "t3/qol-changes", true)));
assertEquals("Dev build df31f1e", BuildFacts.title(
new BuildIdentity(BuildChannel.DEVELOPMENT, COMMIT, "development", "", false)));
}
@Test
public void releaseTitleNamesCommitAndEnvironment() {
assertEquals("Build df31f1e/production", BuildFacts.title(
new BuildIdentity(BuildChannel.RELEASE, COMMIT, "production", "master", true)));
}
@Test
public void jarShowsPathAndDeployAgeAsAnAside() {
DiagnosticFact jar = BuildFacts.jar(new BuildFacts.Jar("plugins/Iris.jar", Optional.of(Duration.ofSeconds(36)), List.of())).orElseThrow();
assertEquals("plugins/Iris.jar, deployed 36s ago", jar.plainValue());
assertTrue(jar.value().contains(ValuePart.muted("deployed 36s ago")));
assertFalse(anyFlagged(jar));
}
@Test
public void secondIrisJarInPluginsIsFlagged() {
DiagnosticFact jar = BuildFacts.jar(new BuildFacts.Jar("plugins/Iris.jar", Optional.empty(),
List.of("Iris-4.3.7.jar"))).orElseThrow();
assertEquals("plugins/Iris.jar, also Iris-4.3.7.jar", jar.plainValue());
assertTrue(flagged(jar, "also Iris-4.3.7.jar"));
}
@Test
public void volmLibStampNamesLocalCheckoutCommit() {
Properties local = new Properties();
local.setProperty("source", "local");
local.setProperty("commit", "8b1775086e4fdd71685e1808e8401c5739d72d53");
local.setProperty("dirty", "true");
Properties published = new Properties();
published.setProperty("source", "published master-SNAPSHOT");
assertEquals("local @ 8b17750+dirty", BuildFacts.volmLib(local).orElseThrow().plainValue());
assertEquals("published master-SNAPSHOT", BuildFacts.volmLib(published).orElseThrow().plainValue());
assertTrue(BuildFacts.volmLib(new Properties()).isEmpty());
}
@Test
public void nativesFlagEverythingThatFellBackToJava() {
DiagnosticFact healthy = BuildFacts.natives(new BuildFacts.Natives("native", BuildFacts.TerrainProvider.NATIVE, "512-bit")).orElseThrow();
DiagnosticFact degraded = BuildFacts.natives(new BuildFacts.Natives("java-library-missing", BuildFacts.TerrainProvider.UNBOUND, "scalar")).orElseThrow();
assertEquals("noise ok, terrain ok, SIMD 512-bit", healthy.plainValue());
assertFalse(anyFlagged(healthy));
assertEquals("noise java-library-missing, terrain failed, SIMD scalar", degraded.plainValue());
assertTrue(flagged(degraded, "noise java-library-missing"));
assertTrue(flagged(degraded, "terrain failed"));
assertTrue(flagged(degraded, "SIMD scalar"));
}
@Test
public void settingsListOnlyWhatDiffersFromTheDefaults() {
IrisSettings changed = new IrisSettings();
changed.getGeneral().setDebug(true);
changed.getStudio().setOpenVSCode(false);
Gson gson = new Gson();
Map<String, String> changes = BuildFacts.settingChanges(gson.toJsonTree(changed), gson.toJsonTree(new IrisSettings()));
assertEquals(Map.of("general.debug", "true", "studio.openVSCode", "false"), changes);
assertEquals("general.debug=true, studio.openVSCode=false", BuildFacts.settings(changes).orElseThrow().plainValue());
}
@Test
public void settingsAreCappedAndDefaultsSaySo() {
Map<String, String> changes = new LinkedHashMap<>();
for (int index = 1; index <= 6; index++) {
changes.put("general.setting" + index, "true");
}
String shown = BuildFacts.settings(changes).orElseThrow().plainValue();
assertTrue(shown, shown.endsWith("general.setting4=true, +2 more"));
assertEquals("defaults", BuildFacts.settings(Map.of()).orElseThrow().plainValue());
}
@Test
public void checksCountByModeAndNameTheUnstableOnes() {
Map<String, String> modes = new LinkedHashMap<>();
modes.put("memory", "stable");
modes.put("diskSpace", "warning");
modes.put("java", "stable");
modes.put("version", "unstable");
DiagnosticFact checks = BuildFacts.checks(modes).orElseThrow();
assertEquals("2 ok, 1 warn (diskSpace), 1 failed (version)", checks.plainValue());
assertTrue(flagged(checks, "1 warn (diskSpace)"));
assertTrue(flagged(checks, "1 failed (version)"));
}
@Test
public void packsFlagWarningsAndFailuresButNotWaiting() {
PackValidationResult clean = new PackValidationResult("cavetest", List.of(), List.of(), 0L);
PackValidationResult warned = new PackValidationResult("riverworld", List.of(), List.of("unknown block"), 0L);
PackValidationResult broken = new PackValidationResult("broken", List.of("missing dimension"), List.of(), 0L);
PackValidationResult waiting = new PackValidationResult("natureplanet", List.of("missing block"), List.of(), 0L);
List<BuildFacts.PackState> states = BuildFacts.packStates(
Map.of("riverworld", warned, "cavetest", clean, "broken", broken, "natureplanet", waiting),
result -> result == waiting);
DiagnosticFact packs = BuildFacts.packs(states).orElseThrow();
assertEquals("broken failed, cavetest ok, natureplanet waiting, riverworld 1 warning", packs.plainValue());
assertTrue(flagged(packs, "broken failed"));
assertTrue(flagged(packs, "riverworld 1 warning"));
assertTrue(packs.value().contains(ValuePart.muted("natureplanet waiting")));
}
}
@@ -0,0 +1,42 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.C;
import art.arcane.iris.localization.ChatReport.ValuePart;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class DiagnosticSectionTest {
private static final DiagnosticSection SECTION = new DiagnosticSection("System", List.of(
new DiagnosticFact("CPU", List.of(ValuePart.warning("8 of 32 threads available"), ValuePart.muted(", "),
ValuePart.warning("limited"))),
new DiagnosticFact("Disk", List.of(ValuePart.plain("world folder 212G free")))));
@Test
public void consoleReportAlignsLabelsAndColorsEachValuePart() {
List<String> lines = SECTION.report().consoleLines();
assertEquals(C.LIGHT_PURPLE + "\u25c6 " + C.LIGHT_PURPLE + "System", lines.get(0));
assertEquals(C.LIGHT_PURPLE + "\u251c " + C.GRAY + C.GRAY + "CPU" + " ".repeat(13)
+ C.GOLD + "8 of 32 threads available" + C.GRAY + ", " + C.GOLD + "limited", lines.get(1));
assertEquals(C.LIGHT_PURPLE + "\u2514 " + C.GRAY + C.GRAY + "Disk" + " ".repeat(12) + C.WHITE + "world folder 212G free",
lines.get(2));
}
@Test
public void plainTextIndentsLabelledFacts() {
assertEquals("System\n CPU: 8 of 32 threads available, limited\n Disk: world folder 212G free", SECTION.plainText());
}
@Test
public void factThatCannotBeDeterminedIsLeftOut() {
DiagnosticSection gathered = DiagnosticSection.gather("System", List.of(
() -> { throw new IllegalStateException("no host"); },
() -> Optional.of(new DiagnosticFact("Disk", List.of(ValuePart.plain("world folder 1G free"))))));
assertEquals(List.of("Disk"), gathered.facts().stream().map(DiagnosticFact::label).toList());
}
}
@@ -0,0 +1,26 @@
package art.arcane.iris.diagnostics;
import org.junit.Test;
import java.time.Duration;
import static org.junit.Assert.assertEquals;
public class FactFormatTest {
@Test
public void ageUsesTheLargestWholeUnit() {
assertEquals("0s", FactFormat.age(Duration.ofSeconds(-5)));
assertEquals("59s", FactFormat.age(Duration.ofSeconds(59)));
assertEquals("1m", FactFormat.age(Duration.ofSeconds(60)));
assertEquals("59m", FactFormat.age(Duration.ofMinutes(59).plusSeconds(59)));
assertEquals("2h", FactFormat.age(Duration.ofHours(2).plusMinutes(30)));
assertEquals("3d", FactFormat.age(Duration.ofDays(3).plusHours(23)));
}
@Test
public void sizeRoundsToWholeGibibytesAndFallsBackToMebibytes() {
assertEquals("6G", FactFormat.size(6L << 30));
assertEquals("124G", FactFormat.size((124L << 30) - (100L << 20)));
assertEquals("512M", FactFormat.size(512L << 20));
}
}
@@ -0,0 +1,87 @@
package art.arcane.iris.diagnostics;
import art.arcane.iris.localization.ChatReport.Emphasis;
import art.arcane.iris.localization.ChatReport.ValuePart;
import org.junit.Test;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.OptionalLong;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SystemFactsTest {
private static boolean anyFlagged(DiagnosticFact fact) {
return fact.value().stream().anyMatch(part -> part.emphasis() == Emphasis.WARNING);
}
@Test
public void cpuWithoutLimitReadsAsFine() {
DiagnosticFact cpu = SystemFacts.cpu(new SystemFacts.Cpu(32, OptionalInt.of(32), Optional.of("Ryzen 9 7950X"))).orElseThrow();
assertEquals("32 of 32 threads available, Ryzen 9 7950X, no limit", cpu.plainValue());
assertFalse(anyFlagged(cpu));
}
@Test
public void cpuLimitBelowHostThreadsIsFlagged() {
DiagnosticFact cpu = SystemFacts.cpu(new SystemFacts.Cpu(8, OptionalInt.of(32), Optional.empty())).orElseThrow();
assertEquals("8 of 32 threads available, limited", cpu.plainValue());
assertTrue(cpu.value().contains(ValuePart.warning("8 of 32 threads available")));
assertTrue(cpu.value().contains(ValuePart.warning("limited")));
}
@Test
public void cpuWithUnknownHostCountShowsWhatTheJvmSees() {
assertEquals("12 threads available", SystemFacts.cpu(new SystemFacts.Cpu(12, OptionalInt.empty(), Optional.empty()))
.orElseThrow().plainValue());
}
@Test
public void cpuModelLosesVendorTrademarksClockAndCoreCount() {
assertEquals("Ryzen 9 7950X", SystemFacts.compactCpuModel(" AMD Ryzen 9 7950X 16-Core Processor"));
assertEquals("Xeon E5-2680 v4", SystemFacts.compactCpuModel("Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz"));
assertEquals("Core i7-8700K", SystemFacts.compactCpuModel("Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz"));
}
@Test
public void poolsLeaveOutPoolsWithoutWorkers() {
assertEquals("generation 16, io 8, pregen 32", SystemFacts.pools(new SystemFacts.Pools(16, 8, 32)).orElseThrow().plainValue());
assertEquals("generation 16, pregen 32", SystemFacts.pools(new SystemFacts.Pools(16, -1, 32)).orElseThrow().plainValue());
}
@Test
public void memoryShowsHeapAgainstHostAndHeadroomAsAnAside() {
DiagnosticFact memory = SystemFacts.memory(new SystemFacts.Memory(6L << 30, OptionalLong.of(124L << 30), OptionalLong.of(52L << 30))).orElseThrow();
assertEquals("heap 6G of 124G host, 52G available", memory.plainValue());
assertTrue(memory.value().contains(ValuePart.muted("52G available")));
}
@Test
public void jvmNamesCollectorPreTouchAndAgent() {
assertEquals("Java 25, G1, pretouch, agent attached", SystemFacts.jvm(new SystemFacts.Jvm(25, Optional.of("G1"), true, true))
.orElseThrow().plainValue());
assertEquals("Java 25, no agent", SystemFacts.jvm(new SystemFacts.Jvm(25, Optional.empty(), false, false))
.orElseThrow().plainValue());
assertEquals("G1", SystemFacts.collectorName("G1 Young Generation"));
assertEquals("Parallel", SystemFacts.collectorName("PS Scavenge"));
assertEquals("ZGC", SystemFacts.collectorName("ZGC Cycles"));
}
@Test
public void osShowsMajorMinorKernelAndContainer() {
assertEquals("Linux 6.18, amd64, container", SystemFacts.os(new SystemFacts.Os("Linux", "6.18.56", "amd64", true))
.orElseThrow().plainValue());
assertEquals("Windows 11 10.0, amd64", SystemFacts.os(new SystemFacts.Os("Windows 11", "10.0", "amd64", false))
.orElseThrow().plainValue());
}
@Test
public void diskShowsFreeSpaceAtTheWorldFolder() {
assertEquals("world folder 212G free", SystemFacts.disk(212L << 30).orElseThrow().plainValue());
}
}
@@ -1,13 +1,12 @@
package art.arcane.iris.diagnostics.splash;
import art.arcane.iris.diagnostics.BuildChannel;
import art.arcane.iris.diagnostics.BuildIdentity;
import art.arcane.iris.pack.BuiltInPackUpdates;
import org.junit.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -15,17 +14,18 @@ import static org.junit.Assert.assertFalse;
public class IrisSplashComposerTest {
private static final String COMMIT = "df31f1e2e5f1c0a8d4b7e9f6a3c2b1d0e9f8a7b6";
private static final int TITLE_ROW = 0;
private static final int VERSION_ROW = 1;
private static final int COMMIT_ROW = 6;
private static SplashBuild release() {
return new SplashBuild(BuildChannel.RELEASE, COMMIT, "production", "master", true, Optional.of(Duration.ofMinutes(3)));
private static BuildIdentity release() {
return new BuildIdentity(BuildChannel.RELEASE, COMMIT, "production", "master", true);
}
private static SplashBuild development(String branch, boolean dirty, Optional<Duration> age) {
return new SplashBuild(BuildChannel.DEVELOPMENT, COMMIT, "development", branch, dirty, age);
private static BuildIdentity development(boolean dirty) {
return new BuildIdentity(BuildChannel.DEVELOPMENT, COMMIT, "development", "t3/qol-changes", dirty);
}
private static String[] plainInfo(SplashBuild build) {
private static String[] plainInfo(BuildIdentity build) {
return IrisSplashComposer.composeInfo("4.3.0-26.2", "Paper 26.2", IrisSplashComposer.InfoStyle.PLAIN, build, List.of());
}
@@ -34,34 +34,26 @@ public class IrisSplashComposerTest {
String[] info = plainInfo(release());
assertEquals(" Iris, Dimension Engine [4.3]", info[TITLE_ROW]);
assertEquals(" Version 4.3.0-26.2", info[VERSION_ROW]);
assertEquals(" Commit df31f1e/production", info[COMMIT_ROW]);
}
@Test
public void developmentBuildShowsTagBranchDirtyFlagAndAge() {
String[] info = plainInfo(development("t3/qol-changes", true, Optional.of(Duration.ofSeconds(200))));
public void developmentBuildShowsTagVersionMarkAndDirtyCommitOnly() {
String[] info = plainInfo(development(true));
assertEquals(" Iris, Dimension Engine [4.3 DEV]", info[TITLE_ROW]);
assertEquals(" Commit df31f1e+dirty Branch t3/qol-changes Built 3m ago", info[COMMIT_ROW]);
assertEquals(" Version 4.3.0-26.2 (dev)", info[VERSION_ROW]);
assertEquals(" Commit df31f1e+dirty", info[COMMIT_ROW]);
}
@Test
public void developmentBuildOmitsMissingBranchAndAge() {
String[] info = plainInfo(development("", false, Optional.empty()));
public void cleanDevelopmentBuildShowsTheBareCommit() {
String[] info = plainInfo(development(false));
assertEquals(" Commit df31f1e", info[COMMIT_ROW]);
}
@Test
public void buildAgeUsesTheLargestWholeUnit() {
assertEquals("0s", IrisSplashComposer.compactAge(Duration.ofSeconds(-5)));
assertEquals("59s", IrisSplashComposer.compactAge(Duration.ofSeconds(59)));
assertEquals("1m", IrisSplashComposer.compactAge(Duration.ofSeconds(60)));
assertEquals("59m", IrisSplashComposer.compactAge(Duration.ofMinutes(59).plusSeconds(59)));
assertEquals("2h", IrisSplashComposer.compactAge(Duration.ofHours(2).plusMinutes(30)));
assertEquals("3d", IrisSplashComposer.compactAge(Duration.ofDays(3).plusHours(23)));
}
@Test
public void updateLinesNameOnlyOutdatedPacks() {
List<IrisSplashPackScanner.SplashPackMetadata> packs = List.of(
@@ -110,7 +102,7 @@ public class IrisSplashComposerTest {
}
};
String[] info = IrisSplashComposer.composeInfo("4.0.0-26.2", "Paper 26.2", marksHeadlines);
String[] info = IrisSplashComposer.composeInfo("4.0.0-26.2", "Paper 26.2", marksHeadlines, release(), List.of());
assertEquals(" Version *4.0.0-26.2", info[1]);
assertEquals(" Web volmitsoftware.com", info[3]);
@@ -23,9 +23,9 @@ public class ConsoleGlyphsTest {
public void asciiConsoleGetsAsciiGlyphsThatKeepTheGutterWidth() {
String gutter = ConsoleGlyphs.CROSS + " failed\n" + ConsoleGlyphs.BRANCH + " item\n" + ConsoleGlyphs.BAR + " more\n"
+ ConsoleGlyphs.LAST_BRANCH + " Loading" + ConsoleGlyphs.ELLIPSIS + "\n" + ConsoleGlyphs.CHECK + " done\n"
+ ConsoleGlyphs.WARNING + " careful";
+ ConsoleGlyphs.WARNING + " careful\n" + ConsoleGlyphs.DIAMOND + " facts";
assertEquals("x failed\n| item\n| more\n` Loading...\n+ done\n! careful",
assertEquals("x failed\n| item\n| more\n` Loading...\n+ done\n! careful\n* facts",
ConsoleGlyphs.forCharset(StandardCharsets.US_ASCII).fit(gutter));
}