diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java index c099cdbe5..e64f2a88a 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java @@ -18,1436 +18,143 @@ package art.arcane.iris; -import java.util.concurrent.CompletionStage; -import art.arcane.volmlib.util.diagnostics.BukkitDebugDump; -import art.arcane.iris.generation.runtime.IrisEngineEffects; -import art.arcane.iris.generation.runtime.IrisWorldManager; - -import art.arcane.iris.generation.runtime.EngineComponentCleanup; -import art.arcane.iris.generation.runtime.EngineEffectsProvider; -import art.arcane.iris.generation.runtime.EnginePlatformHooks; -import art.arcane.iris.generation.runtime.EngineWorldManagerProvider; -import art.arcane.iris.diagnostics.splash.IrisSplashComposer; -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.world.IrisStartupValidation; -import art.arcane.iris.world.IrisStartupAdmissionListener; -import art.arcane.iris.world.BukkitWorldReconciler; -import art.arcane.iris.world.IrisWorldGeneratorResolver; -import art.arcane.iris.world.PendingWorldDeleteQueue; -import art.arcane.iris.world.PendingWorldReplacementManager; -import art.arcane.iris.world.WorldRefusalReporter; -import art.arcane.iris.configuration.SettingsHotloadWatch; -import art.arcane.iris.update.IrisUpdateNotifier; -import art.arcane.iris.pack.datapack.ServerConfigurator; -import art.arcane.iris.pack.datapack.DatapackIngestService; -import art.arcane.iris.pack.datapack.DatapackIngestService.StartupValidationOutcome; -import art.arcane.iris.world.lifecycle.IrisRuntimeStatics; -import art.arcane.iris.world.lifecycle.ManagedWorldLoader; -import art.arcane.iris.world.lifecycle.MissingWorldStorageLog; -import art.arcane.iris.world.lifecycle.PaperLibBootstrap; -import art.arcane.iris.world.lifecycle.WorldLifecycleService; -import art.arcane.iris.world.runtime.BukkitEnginePlatformHooks; -import art.arcane.iris.world.runtime.WorldDeletionQueue; -import art.arcane.iris.world.runtime.WorldRuntimeControlService; -import art.arcane.iris.api.terrain.IrisTerrainService; -import art.arcane.iris.integration.IrisPapiInstaller; -import art.arcane.iris.integration.IrisPapiListener; -import art.arcane.iris.integration.IrisPapiState; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.volmlib.util.director.help.DirectorMiniMenu; -import art.arcane.volmlib.util.localization.BukkitLanguageSwitcher; -import art.arcane.iris.integration.MultiverseCoreLink; -import art.arcane.iris.platform.agent.Agent; -import art.arcane.iris.platform.agent.AttachSignal; -import art.arcane.iris.platform.bukkit.nms.INMS; -import art.arcane.volmlib.nativelib.terrain.ServerShutdownBoundary; -import art.arcane.iris.studio.view.BukkitGuiHost; -import art.arcane.iris.studio.view.GuiHost; -import art.arcane.iris.studio.view.PregeneratorJob; -import art.arcane.iris.platform.bukkit.BoardSVC; -import art.arcane.iris.command.CommandSVC; -import art.arcane.iris.pack.datapack.DatapackStructureScopeSVC; -import art.arcane.iris.studio.edit.EditSVC; -import art.arcane.iris.world.entity.EntityRiseSVC; -import art.arcane.iris.integration.ExternalDataSVC; -import art.arcane.iris.generation.runtime.GlobalCacheSVC; -import art.arcane.iris.platform.bukkit.api.IrisApiEventSVC; -import art.arcane.iris.generation.runtime.IrisEngineSVC; -import art.arcane.iris.integration.IrisIntegrationService; -import art.arcane.iris.platform.protocol.IrisProtocolService; -import art.arcane.iris.platform.bukkit.api.IrisTerrainSVC; -import art.arcane.iris.studio.jigsaw.JigsawStudioService; -import art.arcane.iris.diagnostics.LogFilterSVC; -import art.arcane.iris.integration.MultiverseSVC; -import art.arcane.iris.studio.object.ObjectSVC; -import art.arcane.iris.studio.object.ObjectStudioSaveService; -import art.arcane.iris.generation.runtime.PreservationSVC; -import art.arcane.iris.studio.StudioSVC; -import art.arcane.iris.world.tree.TreeFellerSVC; -import art.arcane.iris.world.tree.TreeSVC; -import art.arcane.iris.studio.wand.WandSVC; -import art.arcane.iris.world.IrisToolbelt; -import art.arcane.iris.generation.runtime.EnginePanic; -import art.arcane.iris.generation.runtime.BlockEditAccess; -import art.arcane.iris.generation.runtime.PreservationRegistry; -import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial; -import art.arcane.iris.pack.validation.IrisCompat; -import art.arcane.iris.world.safeguard.IrisSafeguard; -import art.arcane.iris.world.safeguard.RuntimeLockNotice; -import art.arcane.iris.platform.generation.PlatformChunkGenerator; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.spi.LogLevel; -import art.arcane.volmlib.integration.ReloadAware; -import art.arcane.volmlib.util.bukkit.papi.PlaceholderRegistration; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.exceptions.IrisException; -import art.arcane.iris.localization.C; -import art.arcane.volmlib.util.function.NastyRunnable; -import art.arcane.volmlib.util.hud.HudActionBar; -import art.arcane.volmlib.util.hud.HudBossBarLane; -import art.arcane.volmlib.util.io.IO; -import art.arcane.volmlib.util.io.InstanceState; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.plugin.ComponentLog; -import art.arcane.volmlib.util.plugin.ComponentMessenger; -import art.arcane.volmlib.util.plugin.ComponentText; -import art.arcane.iris.platform.bootstrap.Bindings; -import art.arcane.iris.platform.bootstrap.ServerProperties; -import art.arcane.iris.platform.bootstrap.SlimJar; -import art.arcane.iris.generation.concurrent.MultiBurst; -import art.arcane.iris.platform.bukkit.plugin.IrisService; import art.arcane.iris.platform.bukkit.plugin.VolmitPlugin; import art.arcane.iris.platform.bukkit.plugin.VolmitSender; -import art.arcane.iris.platform.bukkit.chunk.ChunkTickets; -import art.arcane.iris.world.task.J; -import art.arcane.iris.generation.simd.SimdSupport; -import art.arcane.volmlib.util.scheduling.Queue; -import art.arcane.volmlib.util.scheduling.ShurikenQueue; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.Command; +import art.arcane.volmlib.integration.ReloadAware; +import art.arcane.volmlib.util.function.NastyRunnable; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; -import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.generator.BiomeProvider; import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.IllegalPluginAccessException; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileDescriptor; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.Date; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; +import java.util.concurrent.CompletionStage; @SuppressWarnings("CanBeFinal") public class Iris extends VolmitPlugin implements Listener, ReloadAware { - private static final long SERVER_SHUTDOWN_BOUNDARY_TIMEOUT_SECONDS = 300L; - private static final PrintStream SHUTDOWN_ERRORS = new PrintStream(new FileOutputStream(FileDescriptor.err), true); - private static final long SERVER_STOP_PREGEN_TIMEOUT_MILLIS = 30000L; - private static final Queue syncJobs = new ShurikenQueue<>(); - - static { - System.setProperty("iris.cache.fast", "true"); - } - public static Iris instance; - public static MultiverseCoreLink linkMultiverseCore; - public static IrisCompat compat; - public static ChunkTickets tickets; - private static VolmitSender sender; - private static Thread shutdownHook; - private static final StackWalker DEBUG_STACK_WALKER = StackWalker.getInstance(); - static { - try { - InstanceState.updateInstanceId(); - } catch (Throwable ex) { - IrisLogging.reportError("Failed to update the Iris instance id.", ex); - } + private final IrisPluginRuntime runtime; + + public Iris() { + runtime = IrisPluginRuntime.create(this); + runtime.initialize(); } - private static final Object TEARDOWN_LOCK = new Object(); - private final AtomicBoolean alreadyDrained = new AtomicBoolean(false); - private final AtomicBoolean postStopFinisherStarted = new AtomicBoolean(false); - private final AtomicBoolean serverStopTeardownDeferred = new AtomicBoolean(false); - private final AtomicBoolean servicesDisabled = new AtomicBoolean(false); - private final AtomicBoolean runtimeTeardownFailed = new AtomicBoolean(false); - private final AtomicBoolean sharedRuntimeClosed = new AtomicBoolean(false); - private final AtomicBoolean startupBoundaryRestart = new AtomicBoolean(false); - private final AtomicBoolean terminalCleanupCompleted = new AtomicBoolean(false); - private volatile boolean generatorDrainCompleted; - private volatile boolean enableFailed; - private volatile PlaceholderRegistration papiRegistration; - private volatile IrisPapiListener papiListener; - private volatile IrisPapiState papiState; - private volatile boolean papiLifecycleActive; - private KMap, IrisService> services; - // Copy-on-write: mutated on the main thread during enable() and iterated by the JVM - // shutdown-hook thread during teardown; a plain list would CME and abort the teardown. - private final List enabledServices = new CopyOnWriteArrayList<>(); - private final List deferredShutdownGenerators = new CopyOnWriteArrayList<>(); - private final IrisWorldGeneratorResolver generatorResolver = new IrisWorldGeneratorResolver(this); - private final BukkitWorldReconciler worldReconciler = new BukkitWorldReconciler(this); - private final PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this); - private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this); - private BukkitLanguageSwitcher languageSwitcher; - private IrisUpdateNotifier updateNotifier; - private BukkitDebugDump debugDump; - private volatile SettingsHotloadWatch settingsHotloadWatch; - private volatile ServerShutdownBoundary serverShutdownBoundary; - private boolean shutdownProtectionInitialized; + IrisPluginRuntime runtime() { + return runtime; + } + + void enablePlugin() { + super.onEnable(); + } + + void disablePlugin() { + super.onDisable(); + } public static VolmitSender getSender() { - VolmitSender current = sender; - if (current == null) { - Iris plugin = instance; - current = new VolmitSender(Bukkit.getConsoleSender()); - current.setTag(plugin == null ? IrisSafeguard.mode().tag("") : plugin.getTag()); - sender = current; - } - return current; + return IrisPluginRuntime.getSender(); } - @SuppressWarnings("unchecked") - public static T service(Class c) { - Iris plugin = instance; - if (plugin == null || plugin.services == null) { - throw new IllegalStateException("Iris is disabled; " + c.getSimpleName() + " is unavailable"); - } - return (T) plugin.services.get(c); + public static T service(Class type) { + return IrisPluginRuntime.service(type); } - public static void callEvent(Event e) { - Runnable dispatcher = () -> { - try { - Bukkit.getPluginManager().callEvent(e); - } catch (Throwable ex) { - reportError("Event dispatch failed for \"" + e.getEventName() + "\".", ex); - if (ex instanceof RuntimeException runtimeException) { - throw runtimeException; - } - if (ex instanceof Error error) { - throw error; - } - throw new IllegalStateException(ex); - } - }; - if (!e.isAsynchronous()) { - J.s(dispatcher); - } else { - dispatcher.run(); - } + public static void callEvent(Event event) { + IrisPluginRuntime.callEvent(event); } - static boolean isConcreteImplementation(Class candidate, Class requiredType) { - int modifiers = candidate.getModifiers(); - return requiredType.isAssignableFrom(candidate) - && !candidate.isInterface() - && !Modifier.isAbstract(modifiers); + public static void msg(String message) { + IrisPluginRuntime.msg(message); } - public static void sq(Runnable r) { - synchronized (syncJobs) { - syncJobs.queue(r); - } + public static void warn(String format, Object... args) { + IrisPluginRuntime.warn(format, args); } - public static File getTemp() { - Iris plugin = instance; - if (plugin == null) { - throw new IllegalStateException("Iris is disabled; the temp folder is unavailable"); - } - return plugin.getDataFolder("cache", "temp"); + public static void error(String format, Object... args) { + IrisPluginRuntime.error(format, args); } - public static void msg(String string) { - try { - Iris plugin = instance; - ComponentLog.logMarkup( - plugin, - Logger.getLogger("Iris"), - logPrefix(plugin), - Level.INFO, - string, - null); - } catch (Throwable e) { - try { - Iris plugin = instance; - String plainPrefix = ComponentText.legacy(logPrefix(plugin)).plain(); - Logger.getLogger("Iris").log(Level.INFO, plainPrefix + IrisLogging.clean(string)); - } catch (Throwable inner) { - System.err.println("[Iris] Failed to emit log message: " + inner.getMessage()); - inner.printStackTrace(System.err); - } - } + public static void debug(String message) { + IrisPluginRuntime.debug(message); } - /** - * A warning raised here is the same kind of thing as one raised in core, so it takes the same route: the - * plugin logger at WARNING, where a log scan of logs/latest.log finds it. - */ - public static void warn(String format, Object... objs) { - diagnostic(Level.WARNING, safeFormat(format, objs)); + public static void debug(String category, int line, String message) { + IrisPluginRuntime.debug(category, line, message); } - public static void error(String format, Object... objs) { - diagnostic(Level.SEVERE, safeFormat(format, objs)); + public static void verbose(String message) { + IrisPluginRuntime.verbose(message); } - public static void debug(String string) { - if (!IrisSettings.get().getGeneral().isDebug()) { - return; - } - - StackWalker.StackFrame frame; - try { - frame = DEBUG_STACK_WALKER.walk(stream -> stream.skip(1).findFirst().orElse(null)); - } catch (Throwable unavailable) { - frame = null; - } - - if (frame == null) { - debug("Origin", -1, string); - return; - } - - String className = frame.getClassName(); - String[] cc = className == null ? new String[0] : className.split("\\Q.\\E"); - int line = frame.getLineNumber(); - - if (cc.length > 5) { - debug(cc[3] + "/" + cc[4] + "/" + cc[cc.length - 1], line, string); - return; - } - - if (cc.length > 4) { - debug(cc[3] + "/" + cc[4], line, string); - return; - } - - if (cc.length > 0) { - debug(cc[cc.length - 1], line, string); - return; - } - - debug("Origin", line, string); - } - - public static void debug(String category, int line, String string) { - if (!IrisSettings.get().getGeneral().isDebug()) { - return; - } - if (IrisSettings.get().getGeneral().isUseConsoleCustomColors()) { - msg("" + category + " <#bf3b76>" + line + " " + C.LIGHT_PURPLE + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); - } else { - msg(C.BLUE + category + ":" + C.AQUA + line + C.RESET + C.LIGHT_PURPLE + " " + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); - - } - } - - public static void verbose(String string) { - debug(string); - } - - public static void success(String string) { - msg(C.IRIS + string); + public static void success(String message) { + IrisPluginRuntime.success(message); } public static void info(String format, Object... args) { - msg(C.WHITE + safeFormat(format, args)); + IrisPluginRuntime.info(format, args); } - private static String safeFormat(String format, Object... args) { - return IrisLogging.format(format, args); + public static void later(NastyRunnable task) { + IrisPluginRuntime.later(task); } - public static void later(NastyRunnable object) { - try { - J.a(() -> { - try { - object.run(); - } catch (Throwable e) { - Iris.reportError(e); - } - }, RNG.r.i(100, 1200)); - } catch (IllegalPluginAccessException ex) { - Iris.verbose("Skipping deferred task registration because plugin access is unavailable: " - + ex.getClass().getSimpleName() - + (ex.getMessage() == null ? "" : " - " + ex.getMessage())); - } + public static void reportErrorChunk(int x, int z, Throwable failure, String extra) { + IrisPluginRuntime.reportErrorChunk(x, z, failure, extra); } - public static int jobCount() { - return syncJobs.size(); + public static void reportError(Throwable failure) { + IrisPluginRuntime.reportError(failure); } - public static void clearQueues() { - synchronized (syncJobs) { - syncJobs.clear(); - } - } - - public static int getJavaVersion() { - String version = System.getProperty("java.version"); - if (version.startsWith("1.")) { - version = version.substring(2, 3); - } else { - int dot = version.indexOf("."); - if (dot != -1) { - version = version.substring(0, dot); - } - } - return Integer.parseInt(version); - } - - public static String getJava() { - String javaRuntimeName = System.getProperty("java.vm.name"); - String javaRuntimeVendor = System.getProperty("java.vendor"); - String javaRuntimeVersion = System.getProperty("java.vm.version"); - return String.format("%s %s (build %s)", javaRuntimeName, javaRuntimeVendor, javaRuntimeVersion); - } - - public static void reportErrorChunk(int x, int z, Throwable e, String extra) { - if (IrisSettings.get().getGeneral().isDebug()) { - File f = instance.getDataFile("debug", "chunk-errors", "chunk." + x + "." + z + ".txt"); - - if (!f.exists()) { - J.attempt(() -> { - PrintWriter pw = new PrintWriter(f); - pw.println("Thread: " + Thread.currentThread().getName()); - pw.println("First: " + new Date(M.ms())); - e.printStackTrace(pw); - pw.close(); - }); - } - - Iris.debug("Chunk " + x + "," + z + " Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); - } - } - - public static void reportError(Throwable e) { - if (e == null) { - return; - } - if (instance != null && instance.serverStopTeardownDeferred.get()) { - e.printStackTrace(SHUTDOWN_ERRORS); - return; - } - - boolean debug = false; - if (instance != null) { - try { - IrisSettings currentSettings = IrisSettings.settings != null ? IrisSettings.settings : IrisSettings.get(); - debug = currentSettings != null && currentSettings.getGeneral().isDebug(); - } catch (Throwable unreadable) { - debug = false; - } - } - - if (debug) { - String n = e.getClass().getName(); - StackTraceElement[] trace = e.getStackTrace(); - if (trace.length > 0) { - n += "-" + trace[0].getClassName() + "-" + trace[0].getLineNumber(); - } - - if (e.getCause() != null) { - StackTraceElement[] causeTrace = e.getCause().getStackTrace(); - n += "-" + (causeTrace.length == 0 ? e.getCause().getClass().getName() - : causeTrace[0].getClassName() + "-" + causeTrace[0].getLineNumber()); - } - - File f = instance.getDataFile("debug", "caught-exceptions", n + ".txt"); - - if (!f.exists()) { - J.attempt(() -> { - PrintWriter pw = new PrintWriter(f); - pw.println("Thread: " + Thread.currentThread().getName()); - pw.println("First: " + new Date(M.ms())); - e.printStackTrace(pw); - pw.close(); - }); - } - - Iris.debug("Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); - } - - e.printStackTrace(System.err); - } - - public static void reportError(String context, Throwable e) { - Throwable error = e == null ? new IllegalStateException("Unknown Iris failure") : e; - String message = context == null || context.isBlank() ? "Unhandled Iris failure." : context; - if (instance != null && instance.serverStopTeardownDeferred.get()) { - SHUTDOWN_ERRORS.println("[Iris] " + message); - error.printStackTrace(SHUTDOWN_ERRORS); - return; - } - - try { - if (instance != null) { - Iris.error(message); - } else { - System.err.println("[Iris] " + message); - } - } catch (Throwable inner) { - System.err.println("[Iris] " + message); - inner.printStackTrace(System.err); - } - - reportError(error); + public static void reportError(String context, Throwable failure) { + IrisPluginRuntime.reportError(context, failure); } public static void dump() { - try { - File fi = Iris.instance.getDataFile("dump", "td-" + new java.sql.Date(M.ms()) + ".txt"); - FileOutputStream fos = new FileOutputStream(fi); - Map f = Thread.getAllStackTraces(); - PrintWriter pw = new PrintWriter(fos); - for (Thread i : f.keySet()) { - pw.println("========================================"); - pw.println("Thread: '" + i.getName() + "' ID: " + i.threadId() + " STATUS: " + i.getState().name()); - - for (StackTraceElement j : f.get(i)) { - pw.println(" @ " + j.toString()); - } - - pw.println("========================================"); - pw.println(); - pw.println(); - } - pw.println("[%%__USER__%%,%%__RESOURCE__%%,%%__PRODUCT__%%,%%__BUILTBYBIT__%%]"); - - pw.close(); - Iris.info("DUMPED! See " + fi.getAbsolutePath()); - } catch (Throwable e) { - Iris.reportError("Failed to write the Iris thread dump.", e); - } + IrisPluginRuntime.dump(); } public static void panic() { - EnginePanic.panic(); - } - - public static void addPanic(String s, String v) { - EnginePanic.add(s, v); - } - - public Iris() { - instance = this; - BukkitPlatform.hostPlugin(this); - BukkitPlatform.hostConsoleSender(Iris::getSender); - BukkitPlatform.hostBridge(new BukkitPlatform.HostBridge( - Iris::bridgeLog, - Iris::msg, - Iris::reportError, - (event) -> Iris.callEvent((org.bukkit.event.Event) event), - this::getDataFolder, - this::getDataFile, - this::getJarFile, - this::getIrisVersion, - this::getMCVersion)); - SlimJar.load(); - restoreAttachSignal(); - } - - private static void restoreAttachSignal() { - try { - if (AttachSignal.restoreJvmHandler()) { - info("Restored the JVM SIGQUIT handler that the server console replaced"); - } - } catch (RuntimeException failure) { - reportError("Could not restore the JVM SIGQUIT handler; the Iris agent may fail to attach.", failure); - } - } - - private static void bridgeLog(LogLevel level, String message) { - LogLevel target = level == null ? LogLevel.INFO : level; - Level diagnostic = diagnosticLevel(target); - if (diagnostic != null) { - diagnostic(diagnostic, message); - return; - } - if (target == LogLevel.DEBUG) { - Iris.debug(message); - return; - } - Iris.info(message); - } - - /** - * The java.util.logging level a message keeps, or null when it belongs on the console sender path. - *

- * Core states a severity and every other adapter honours it; on Bukkit a coloured line through the - * console sender reaches the terminal but not the instance's logs/latest.log, so a WARN-level scan of - * that file never saw a single core warning. Diagnostics go to the plugin logger at their own level - * instead, and NOTICE carries the handful of lifecycle lines that have to land there too. Player-facing - * text still goes through {@code IrisLogging.msg}. - */ - static Level diagnosticLevel(LogLevel level) { - return switch (level) { - case NOTICE -> Level.INFO; - case WARN -> Level.WARNING; - case ERROR -> Level.SEVERE; - case DEBUG, INFO -> null; - }; - } - - private static void diagnostic(Level level, String message) { - String line = IrisLogging.clean(message); - Iris plugin = instance; - ComponentLog.log( - plugin, - Logger.getLogger("Iris"), - logPrefix(plugin), - level, - ComponentText.literal(line), - null); - } - - private static String logPrefix(Iris plugin) { - return plugin == null ? ComponentLog.discriminator("Iris", "&a") : plugin.getTag(); - } - - private void enable() { - EnableTimings timings = new EnableTimings(); - alreadyDrained.set(false); - postStopFinisherStarted.set(false); - serverStopTeardownDeferred.set(false); - servicesDisabled.set(false); - runtimeTeardownFailed.set(false); - sharedRuntimeClosed.set(false); - startupBoundaryRestart.set(false); - terminalCleanupCompleted.set(false); - generatorDrainCompleted = false; - deferredShutdownGenerators.clear(); - MultiBurst.burst.reopen(); - MultiBurst.hydrology.reopen(); - MultiBurst.ioBurst.reopen(); - IrisLanguage.initialize(); - debugDump = BukkitDebugDump.create(this, new BukkitDebugDump.Options( - () -> true, - () -> IrisSafeguard::debugReport)); - languageSwitcher = BukkitLanguageSwitcher.register(this, IrisLanguage.selections(), - new BukkitLanguageSwitcher.Options("iris", "iris.all", - DirectorMiniMenu.Theme.irisGreen(), IrisLanguage.directorResolver(), IrisLanguage.editorOptions())); - updateNotifier = new IrisUpdateNotifier(this); - PaperLibBootstrap.install(); - SimdSupport.install(); - timings.mark("bootstrap"); - services = new KMap<>(); - BukkitPlatform.hostHud(new HudActionBar(this), new HudBossBarLane()); - // Explicit, ordered service list: the previous reflective jar scan gave hash-ordered - // enable/disable and paid a full-jar class sweep at boot. Infrastructure first, - // engine/world services next, commands last. - List orderedServices = List.of( - new PreservationSVC(), - new GlobalCacheSVC(), - new LogFilterSVC(), - new ExternalDataSVC(), - new EditSVC(), - new ObjectSVC(), - new ObjectStudioSaveService(), - new JigsawStudioService(), - new StudioSVC(), - new DatapackStructureScopeSVC(), - new IrisEngineSVC(), - new IrisTerrainSVC(), - new TreeSVC(), - new TreeFellerSVC(), - new EntityRiseSVC(), - new WandSVC(), - new BoardSVC(), - new IrisIntegrationService(), - new MultiverseSVC(), - new IrisProtocolService(), - new IrisApiEventSVC(), - new CommandSVC() - ); - for (IrisService i : orderedServices) { - Class serviceType = i.getClass().asSubclass(IrisService.class); - services.put(serviceType, i); - IrisServices.register(serviceType, i); - } - IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class)); - IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class)); - compat = IrisCompat.configured(getDataFile("compat.json")); - IrisServices.register(IrisCompat.class, compat); - timings.mark("services"); - ServerConfigurator.configure(); - timings.mark("serverConfig"); - StartupValidationOutcome datapackValidation = DatapackIngestService.validateOnStartup(); - timings.mark("datapacks"); - IrisSafeguard.execute(); - timings.mark("safeguard"); - getSender().setTag(getTag()); - // A cosmetic banner must never abort the bootstrap. - J.attempt(this::splash); - IrisSafeguard.printReports(); - IrisSafeguard.printFooter(); - // Paper's bootstrap runs before any plugin logger exists, so orphan-storage warnings raised there - // never reach logs/latest.log. Replay them once now that the platform log is up. - MissingWorldStorageLog.replayToPlatformLog(); - timings.mark("splash"); - tickets = new ChunkTickets(); - linkMultiverseCore = new MultiverseCoreLink(); - IrisServices.register(MultiverseCoreLink.class, linkMultiverseCore); - IrisServices.register(EngineComponentCleanup.class, (EngineComponentCleanup) BukkitPlatform::unregisterListener); - IrisServices.register(EngineEffectsProvider.class, (EngineEffectsProvider) IrisEngineEffects::new); - IrisServices.register(EnginePlatformHooks.class, new BukkitEnginePlatformHooks()); - IrisServices.register(EngineWorldManagerProvider.class, - (EngineWorldManagerProvider) IrisWorldManager::new); - IrisServices.register(WorldDeletionQueue.class, pendingWorldDeletes); - IrisServices.register(ManagedWorldLoader.class, (ManagedWorldLoader) this::loadManagedWorld); - SettingsHotloadWatch watch = new SettingsHotloadWatch(getDataFile("iris.json")); - settingsHotloadWatch = watch; - StudioSVC.gateDownloadsOnStaleTempCleanup(MultiBurst.ioBurst.completeValueAsync(() -> { - IO.delete(getTemp()); - return null; - })); - timings.mark("tempSweep"); - // One throwing service must not abort the bootstrap: the steps after this loop - // (listeners, shutdown hook, replacement journals) are the safety-critical ones. - // Only services that actually enabled get listeners and a later onDisable. - enabledServices.clear(); - for (IrisService service : orderedServices) { - long serviceStartedAt = System.nanoTime(); - try { - service.onEnable(); - enabledServices.add(service); - timings.markService(service.getClass().getSimpleName(), serviceStartedAt); - } catch (Throwable e) { - // A service failure is NOT a datapack validation failure: the admission gate - // must never lock every login over a broken cosmetic service. Log loudly, - // continue degraded, and clean up whatever the partial onEnable started - // (a failed service is excluded from the teardown loop). - Iris.reportError("Failed to enable " + service.getClass().getSimpleName() + "; continuing with a degraded runtime.", e); - try { - service.onDisable(); - } catch (Throwable cleanup) { - Iris.reportError("Failed to clean up partially enabled " + service.getClass().getSimpleName() + ".", cleanup); - } - } - } - for (IrisService service : enabledServices) { - try { - registerListener(service); - } catch (Throwable e) { - Iris.reportError("Failed to register listener for " + service.getClass().getSimpleName() + ".", e); - } - } - timings.mark("serviceEnable"); - if (datapackValidation == StartupValidationOutcome.READY) { - IrisServices.get(ExternalDataSVC.class).setContentChangeListener(generatorResolver::requestExternalContentRefresh); - generatorResolver.validateAllPacks(); - } - timings.mark("packValidation"); - addShutdownHook(); - pendingWorldReplacements.processPendingStartupReplacements(); - pendingWorldDeletes.processPendingStartupWorldDeletes(); - - if (J.isFolia() && IrisStartupValidation.isReady()) { - J.s(this::reconcileStartupWorlds, 1); - } - - J.s(() -> { - pendingWorldReplacements.captureVanillaLevelContext(); - pendingWorldReplacements.verifyLoadedPublishedWorlds(); - J.a(this::bstats); - J.ar(watch::checkConfigHotload, 10); - J.sr(this::tickQueue, 0); - J.s(this::setupPapi); - if (IrisStartupValidation.isReady()) { - J.a(DatapackIngestService::runPostStartupTasks, 60); - autoStartStudio(); - } - if (!J.isFolia() && IrisStartupValidation.isReady()) { - reconcileStartupWorlds(); - } - IrisToolbelt.retainMantleDataForSlice(String.class.getCanonicalName()); - // The mantle stores block values as NativeBlockState, so a BlockData retention can never - // match a slice type; the block-state slice is deliberately never retainable (regenerable, huge). - IrisToolbelt.retainMantleDataForSlice(TreeBlockMaterial.class.getCanonicalName()); - }); - timings.mark("startupTasks"); - timings.report(); - } - - private static final class EnableTimings { - private static final int REPORTED_SERVICES = 3; - - private final long startedAt = System.nanoTime(); - private final StringBuilder phases = new StringBuilder(); - private final Map serviceMillis = new LinkedHashMap<>(); - private long lastMark = startedAt; - - private void mark(String phase) { - long now = System.nanoTime(); - if (!phases.isEmpty()) { - phases.append(' '); - } - phases.append(phase).append('=').append(TimeUnit.NANOSECONDS.toMillis(now - lastMark)).append("ms"); - lastMark = now; - } - - private void markService(String service, long serviceStartedAt) { - serviceMillis.put(service, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - serviceStartedAt)); - } - - private void report() { - IrisLogging.notice("Enabled in %dms (%s)", - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt), phases); - String slowest = serviceMillis.entrySet().stream() - .sorted(Map.Entry.comparingByValue().reversed()) - .limit(REPORTED_SERVICES) - .map(entry -> entry.getKey() + "=" + entry.getValue() + "ms") - .collect(Collectors.joining(" ")); - if (!slowest.isBlank()) { - IrisLogging.notice("Slowest services: %s", slowest); - } - } - } - - private void reconcileStartupWorlds() { - generatorResolver.startupWorldsReady().whenComplete((ignored, failure) -> { - if (failure != null) { - Iris.reportError("Could not resume Iris startup world reconciliation.", failure); - return; - } - J.s(() -> worldReconciler.checkForBukkitWorlds(s -> true)); - }); - } - - public void addShutdownHook() { - removeShutdownHook(); - serverShutdownBoundary = INMS.isBound() ? INMS.get().createServerShutdownBoundary() : null; - shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook"); - try { - Runtime.getRuntime().addShutdownHook(shutdownHook); - } catch (IllegalStateException ex) { - Iris.debug("Skipping shutdown hook registration because JVM shutdown is already in progress."); - } - } - - /** - * The static-field guard in addShutdownHook is dead across a plugin reload (fresh - * classloader, fresh static), so onDisable must deregister the hook explicitly or each - * reload stacks another hook pinning the previous plugin classloader for the JVM's life. - */ - public void removeShutdownHook() { - Thread hook = shutdownHook; - shutdownHook = null; - if (hook == null) { - return; - } - try { - Runtime.getRuntime().removeShutdownHook(hook); - } catch (IllegalStateException ignored) { - Iris.debug("Skipping shutdown hook removal because JVM shutdown is already in progress."); - } - } - - public BukkitWorldReconciler worldReconciler() { - return worldReconciler; - } - - /** - * The load every integration goes through. {@code /iris load} and the Multiverse guard both land here, - * so a world loaded from outside Iris still gets the keyed creator, the pack's environment and the - * bukkit.yml reconciliation that make it an Iris world rather than a vanilla one under the same name. - */ - private CompletableFuture loadManagedWorld(String configuredWorldName) { - return worldReconciler.loadWorld(ServerProperties.BUKKIT_YML, configuredWorldName) - .thenApply(this::managedWorldLoadResult); - } - - private ManagedWorldLoader.ManagedWorldLoad managedWorldLoadResult(BukkitWorldReconciler.LoadResult result) { - if (!result.succeeded() && result.failure() != null) { - reportError("Could not explicitly load Iris world " + result.worldKey() + ": " + result.message(), result.failure()); - } - return new ManagedWorldLoader.ManagedWorldLoad(result.succeeded(), result.message()); - } - - public PendingWorldReplacementManager pendingWorldReplacements() { - return pendingWorldReplacements; - } - - private void autoStartStudio() { - if (IrisSettings.get().getStudio().isAutoStartDefaultStudio()) { - Iris.debug("Starting up auto Studio!"); - try { - Player r = new KList<>(getServer().getOnlinePlayers()).getRandom(); - Iris.service(StudioSVC.class).open(r != null ? new VolmitSender(r) : getSender(), 1337, IrisSettings.get().getGenerator().getDefaultWorldType(), (w) -> { - J.s(() -> { - final Location spawn = w.getSpawnLocation(); - for (Player i : getServer().getOnlinePlayers()) { - final Runnable playerTask = () -> { - i.setGameMode(GameMode.SPECTATOR); - BukkitPlatform.teleportAsync(i, spawn); - }; - if (!J.runEntity(i, playerTask)) { - playerTask.run(); - } - } - }); - }); - } catch (IrisException e) { - reportError(e); - } - } + IrisPluginRuntime.panic(); } + @Override public void onEnable() { - enableFailed = false; - shutdownProtectionInitialized = false; - IrisStartupValidation.begin(); - Bukkit.getPluginManager().registerEvents(new IrisStartupAdmissionListener(), this); - try { - generatorResolver.refusals().attach(this); - IrisPlatforms.bind(new BukkitPlatform()); - Bukkit.getPluginManager().registerEvents(pendingWorldReplacements, this); - pendingWorldReplacements.registerPlatformEntryListener(); - if (!INMS.isBound()) { - refuseUnsupportedServer(); - return; - } - initializeShutdownProtection(); - enable(); - } catch (Throwable failure) { - enableFailed = true; - if (!FailedEnableLock.engage(failure, FailedEnableLock.irisWorldsPresent(), - generatorResolver.refusals().startupWorldsCreated())) { - throw failure; - } - return; - } - BukkitGuiHost.install(); - // super.onEnable() already registers this instance as a listener. - super.onEnable(); - if (IrisStartupValidation.isRestartRequired()) { - String restartReason = IrisStartupValidation.denialReason() - .orElse("Iris startup validation requires a restart."); - startupBoundaryRestart.set(true); - ServerConfigurator.restartAtStartupBoundary(restartReason); - return; - } - papiLifecycleActive = true; - setupPapi(); - reportLockedRuntime(); - } - - private void initializeShutdownProtection() { - if (!INMS.get().supportsIrisWorldGeneration()) { - return; - } - if (!Agent.install()) { - throw new IllegalStateException("Iris Java agent is unavailable; shutdown protection cannot be installed."); - } - INMS.get().initializeLifecycle(getClass().getClassLoader()); - shutdownProtectionInitialized = true; - } - - private void refuseUnsupportedServer() { - Throwable bindFailure = INMS.bindFailure(); - IllegalStateException failure = new IllegalStateException("Iris cannot start: " + (bindFailure == null - ? "no NMS binding is available for this server version." - : bindFailure.getMessage()), bindFailure); - if (FailedEnableLock.engage(failure, FailedEnableLock.irisWorldsPresent(), - generatorResolver.refusals().startupWorldsCreated())) { - enableFailed = true; - return; - } - Iris.error(failure.getMessage()); - // Deferred one tick: disablePlugin from inside onEnable re-enters onDisable - // synchronously and the loader then continues registering the half-enabled plugin. - J.s(() -> Bukkit.getPluginManager().disablePlugin(this), 1); - } - - private static void reportLockedRuntime() { - String denial = IrisStartupValidation.denialReason().orElse(null); - if (denial == null) { - return; - } - for (String line : RuntimeLockNotice.compose(denial, FailedEnableLock.irisWorldsPresent())) { - Iris.error(line); - } - } - - public BukkitDebugDump debugDump() { - return debugDump; - } - - public void selectLanguage(CommandSender sender, String[] arguments) { - BukkitLanguageSwitcher current = languageSwitcher; - if (current != null) { - current.command(sender, arguments); - } - } - - public List completeLanguage(CommandSender sender, String[] arguments) { - BukkitLanguageSwitcher current = languageSwitcher; - return current == null ? List.of() : current.complete(sender, arguments); + runtime.onEnable(); } + @Override public void onDisable() { - pendingWorldReplacements.awaitStagingForShutdown(); - GuiHost.shutdown(); - preservePendingBlockDrops(); - papiLifecycleActive = false; - if (updateNotifier != null) { - updateNotifier.close(); - updateNotifier = null; - } - if (debugDump != null) { - debugDump.close(); - debugDump = null; - } - if (languageSwitcher != null) { - languageSwitcher.close(); - languageSwitcher = null; - } - IrisLanguage.shutdown(); - teardownPapi(); - boolean deferToServerStop = FailedEnableLock.defersTeardownToServerStop(enableFailed, IrisToolbelt.isServerStopping()) - && tryDeferPluginClassLoaderClose(); - boolean restartingAtStartupBoundary = startupBoundaryRestart.get(); - if (restartingAtStartupBoundary) { - teardownRuntime("startup-boundary-restart", 30L); - } else if (deferToServerStop) { - quiesceRuntimeForServerShutdown("onDisable"); - startPostStopFinisher(); - } else { - teardownRuntime("onDisable", 30L); - removeShutdownHook(); - } - if (BukkitPlatform.hasHud()) { - BukkitPlatform.hudBar().shutdown(); - BukkitPlatform.hudLanes().shutdown(); - } - SettingsHotloadWatch activeSettingsHotloadWatch = settingsHotloadWatch; - settingsHotloadWatch = null; - if (activeSettingsHotloadWatch != null) { - activeSettingsHotloadWatch.close(); - } - // super.onDisable() cancels plugin tasks and unregisters every listener. - super.onDisable(); - if (!deferToServerStop || restartingAtStartupBoundary) { - finishTerminalCleanup(); - } + runtime.onDisable(); } @Override public CompletionStage commitReload(ReloadAware.PreUnloadReason reason) { - preservePendingBlockDrops(); - papiLifecycleActive = false; - teardownPapi(); - if (IrisToolbelt.isServerStopping() && tryDeferPluginClassLoaderClose()) { - quiesceRuntimeForServerShutdown("pre-unload:" + reason); - startPostStopFinisher(); - Iris.debug("Pre-unload hook deferred generator teardown until Paper closes its chunk schedulers."); - return CompletableFuture.completedFuture(null); - } - if (alreadyDrained.get()) { - Iris.debug("Pre-unload hook skipped; Iris already drained."); - return CompletableFuture.completedFuture(null); - } - Iris.debug("BileTools pre-unload hook fired (" + reason + "). Freezing all Iris worlds."); - drainOnce("pre-unload:" + reason, 45L); - return CompletableFuture.completedFuture(null); + return runtime.commitReload(reason); } - private boolean tryDeferPluginClassLoaderClose() { - if (!shutdownProtectionInitialized) { - return false; - } - try { - INMS.get().deferPluginClassLoaderClose(); - return true; - } catch (RuntimeException | LinkageError failure) { - Iris.reportError("Failed to retain the Iris plugin class loader; draining shutdown inline.", failure); - return false; - } + public void selectLanguage(CommandSender sender, String[] arguments) { + runtime.selectLanguage(sender, arguments); } - /** - * Drains the world generators exactly once. Serialized against the JVM shutdown hook so a - * second caller cannot rip the pools or services out from under an in-flight drain. - */ - private void drainOnce(String reason, long timeoutSeconds) { - synchronized (TEARDOWN_LOCK) { - if (alreadyDrained.compareAndSet(false, true)) { - drainWorldGenerators(reason, timeoutSeconds); - } - } - } - - /** - * Full teardown: generators, then services, then the shared pools and the service map. - * Both onDisable and the JVM shutdown hook route through here; whichever runs second is a no-op. - */ - private void teardownRuntime(String reason, long timeoutSeconds) { - synchronized (TEARDOWN_LOCK) { - if (alreadyDrained.compareAndSet(false, true)) { - drainWorldGenerators(reason, timeoutSeconds); - } - - if (serverStopTeardownDeferred.get() && !generatorDrainCompleted) { - return; - } - - if (services != null && servicesDisabled.compareAndSet(false, true)) { - // Only services whose onEnable actually completed; disabling a service that - // never initialized runs teardown against uninitialized state. - for (IrisService service : enabledServices) { - try { - service.onDisable(); - } catch (Throwable e) { - runtimeTeardownFailed.set(true); - Iris.reportError("Failed to disable " + service.getClass().getSimpleName() + ".", e); - } - } - } - - if (!sharedRuntimeClosed.compareAndSet(false, true)) { - return; - } - - try { - MultiBurst.burst.close(); - } catch (Throwable failure) { - Iris.reportError("Failed to close Iris generation workers.", failure); - } - try { - MultiBurst.hydrology.close(); - } catch (Throwable failure) { - Iris.reportError("Failed to close Iris hydrology workers.", failure); - } - try { - MultiBurst.ioBurst.close(); - } catch (Throwable failure) { - Iris.reportError("Failed to close Iris I/O workers.", failure); - } - clearQueues(); - IrisRuntimeStatics.reset(); - releaseStatics(); - } - } - - private static void releaseStatics() { - linkMultiverseCore = null; - compat = null; - tickets = null; - sender = null; - instance = null; - } - - private void quiesceRuntimeForServerShutdown(String reason) { - serverStopTeardownDeferred.set(true); - JigsawStudioService jigsawStudioService = IrisServices.getOrNull(JigsawStudioService.class); - if (jigsawStudioService != null) { - try { - jigsawStudioService.quiesceForServerShutdown(); - } catch (Throwable e) { - Iris.reportError("Failed to quiesce Jigsaw Studio before server shutdown.", e); - } - } - StudioSVC studioService = IrisServices.getOrNull(StudioSVC.class); - if (studioService != null) { - studioService.quiesceDownloadsForShutdown(); - } - - try { - if (J.isFolia()) { - PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS); - } else { - List worlds = Bukkit.getWorlds(); - PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS, () -> { - for (World world : worlds) { - INMS.get().pollChunkTask(world); - } - }); - } - } catch (Throwable e) { - Iris.reportError("Failed to quiesce the Iris pregenerator before server shutdown.", e); - } - - for (World world : Bukkit.getWorlds()) { - PlatformChunkGenerator generator = IrisToolbelt.access(world); - if (generator == null) { - continue; - } - IrisToolbelt.beginWorldMaintenance(world, reason); - if (!deferredShutdownGenerators.contains(generator)) { - deferredShutdownGenerators.add(generator); - } - generator.quiesceForServerShutdown(); - } - } - - private void startPostStopFinisher() { - if (!postStopFinisherStarted.compareAndSet(false, true)) { - return; - } - Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"), - "Iris-PostStop-Finisher"); - finisher.setDaemon(false); - finisher.start(); - } - - private void runShutdownHook() { - if (startupBoundaryRestart.get()) { - finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L); - return; - } - finishRuntimeAfterServerShutdown("shutdown-hook"); - } - - private void finishRuntimeAfterServerShutdown(String reason) { - if (!awaitServerShutdownBoundary()) { - SHUTDOWN_ERRORS.println("[Iris] The server did not reach its post-world-close boundary; retaining the runtime and plugin class loader until JVM exit."); - return; - } - finishDeferredRuntimeTeardown(reason, 30L); - } - - private boolean awaitServerShutdownBoundary() { - ServerShutdownBoundary boundary = serverShutdownBoundary; - if (boundary == null) { - return false; - } - try { - return boundary.await( - SERVER_SHUTDOWN_BOUNDARY_TIMEOUT_SECONDS, - TimeUnit.SECONDS - ); - } catch (Throwable e) { - SHUTDOWN_ERRORS.println("[Iris] Failed to await Paper's post-world-close shutdown boundary."); - e.printStackTrace(SHUTDOWN_ERRORS); - return false; - } - } - - private void finishDeferredRuntimeTeardown(String reason, long timeoutSeconds) { - teardownRuntime(reason, timeoutSeconds); - if (serverStopTeardownDeferred.get() && !generatorDrainCompleted) { - SHUTDOWN_ERRORS.println("[Iris] Runtime cleanup is incomplete; retaining services, pools and the plugin class loader until JVM exit."); - return; - } - finishTerminalCleanup(); - } - - private void finishTerminalCleanup() { - if (!terminalCleanupCompleted.compareAndSet(false, true)) { - return; - } - try { - if (INMS.isBound()) { - INMS.get().uninjectBukkit(); - } - } catch (Throwable failure) { - Iris.reportError("Failed to remove Iris world-generation hooks.", failure); - } - try { - runPostShutdown(); - } catch (Throwable e) { - runtimeTeardownFailed.set(true); - Iris.reportError("Failed to run Iris post-shutdown cleanup.", e); - } finally { - boolean activeResources = serverStopTeardownDeferred.get() - && (runtimeTeardownFailed.get() || hasActiveShutdownResources()); - IrisPlatforms.unbind(); - BukkitPlatform.releaseHost(); - if (activeResources) { - SHUTDOWN_ERRORS.println("[Iris] Owned background work has not completed cleanup; retaining the plugin class loader until JVM exit."); - } else { - try { - if (shutdownProtectionInitialized) { - INMS.get().releasePluginClassLoaderClose(); - } else { - SlimJar.closeNativeProviders(); - } - } catch (Throwable failure) { - SHUTDOWN_ERRORS.println("[Iris] Failed to release the plugin class loader after runtime cleanup."); - failure.printStackTrace(SHUTDOWN_ERRORS); - } - } - } - } - - private boolean hasActiveShutdownResources() { - if (!MultiBurst.burst.isTerminated() || !MultiBurst.hydrology.isTerminated() - || !MultiBurst.ioBurst.isTerminated()) { - return true; - } - return services != null - && services.get(PreservationSVC.class) instanceof PreservationSVC preservation - && preservation.hasActiveResources(); - } - - private void preservePendingBlockDrops() { - for (World world : Bukkit.getWorlds()) { - PlatformChunkGenerator generator = IrisToolbelt.access(world); - if (generator != null && generator.getEngine() != null - && generator.getEngine().getWorldManager() instanceof IrisWorldManager manager) { - manager.flushPendingBlockDropsAsync().whenComplete((ignored, failure) -> { - if (failure != null) { - Iris.reportError("Failed to preserve pending block loot before Iris teardown.", failure); - } - }); - } - } - } - - private void drainWorldGenerators(String reason, long timeoutSeconds) { - List irisWorlds = new ArrayList<>(); - List generators = new ArrayList<>(); - if (serverStopTeardownDeferred.get()) { - generators.addAll(deferredShutdownGenerators); - } else { - for (World world : Bukkit.getWorlds()) { - PlatformChunkGenerator generator = IrisToolbelt.access(world); - if (generator != null) { - irisWorlds.add(world); - generators.add(generator); - } - } - } - if (generators.isEmpty()) { - generatorDrainCompleted = true; - Iris.debug("No Iris worlds to freeze."); - return; - } - - for (World world : irisWorlds) { - IrisToolbelt.beginWorldMaintenance(world, reason, true); - } - - J.attempt(PregeneratorJob::shutdownInstance); - - List> closes = new ArrayList<>(); - for (PlatformChunkGenerator generator : generators) { - try { - closes.add(generator.closeAsync()); - } catch (Throwable t) { - Iris.reportError(t); - } - } - - if (closes.isEmpty()) return; - - try { - CompletableFuture.allOf(closes.toArray(new CompletableFuture[0])) - .get(timeoutSeconds, TimeUnit.SECONDS); - generatorDrainCompleted = closes.size() == generators.size(); - if (generatorDrainCompleted) { - Iris.debug("All Iris chunk generators parked. Safe to unload."); - } - } catch (TimeoutException e) { - Iris.reportError("Iris generator drain timed out after " + timeoutSeconds + "s.", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - Iris.reportError("Iris generator drain was interrupted.", e); - } catch (ExecutionException e) { - Iris.reportError(e.getCause() == null ? e : e.getCause()); - } + public List completeLanguage(CommandSender sender, String[] arguments) { + return runtime.completeLanguage(sender, arguments); } @EventHandler public void onPlaceholderApiEnable(PluginEnableEvent event) { - if ("PlaceholderAPI".equals(event.getPlugin().getName())) { - setupPapi(); - } + runtime.onPlaceholderApiEnable(event); } @EventHandler public void onPlaceholderApiDisable(PluginDisableEvent event) { - if ("PlaceholderAPI".equals(event.getPlugin().getName())) { - teardownPapi(); - } - } - - private synchronized void setupPapi() { - if (!papiLifecycleActive || papiRegistration != null - || !PlaceholderRegistration.isPlaceholderApiEnabled()) { - return; - } - - IrisPapiState state = new IrisPapiState(() -> IrisServices.getOrNull(IrisTerrainService.class)); - PlaceholderRegistration registration = new PlaceholderRegistration(getLogger()); - - if (!IrisPapiInstaller.install(registration, state, getLogger())) { - return; - } - - IrisPapiListener listener = new IrisPapiListener(state); - - try { - Bukkit.getPluginManager().registerEvents(listener, this); - } catch (Throwable failure) { - registration.unregister(); - Iris.warn("Failed to attach the Iris PlaceholderAPI listener: " - + failure.getClass().getName() + ": " + failure.getMessage()); - return; - } - - papiState = state; - papiListener = listener; - papiRegistration = registration; - } - - private synchronized void teardownPapi() { - IrisPapiListener listener = papiListener; - papiListener = null; - - if (listener != null) { - HandlerList.unregisterAll(listener); - } - - PlaceholderRegistration registration = papiRegistration; - papiRegistration = null; - - if (registration != null) { - registration.unregister(); - } - - IrisPapiState state = papiState; - papiState = null; - - if (state != null) { - state.clear(); - } + runtime.onPlaceholderApiDisable(event); } @Override @@ -1462,109 +169,20 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { @Override public String getTag(String subTag) { - return IrisSafeguard.mode().tag(subTag); - } - - private void tickQueue() { - synchronized (Iris.syncJobs) { - if (!Iris.syncJobs.hasNext()) { - return; - } - - long ms = M.ms(); - - while (Iris.syncJobs.hasNext() && M.ms() - ms < 25) { - try { - Iris.syncJobs.next().run(); - } catch (Throwable e) { - Iris.reportError(e); - } - } - } - } - - private void bstats() { - if (IrisSettings.get().getGeneral().isMetrics()) { - Bindings.setupBstats(this); - } + return IrisPluginRuntime.tag(subTag); } @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - return super.onCommand(sender, command, label, args); + public BiomeProvider getDefaultBiomeProvider(String worldName, String id) { + return runtime.getDefaultBiomeProvider(worldName, id); } - public void imsg(CommandSender s, String msg) { - ComponentMessenger.sendSection( - s, - C.IRIS + "[" + C.DARK_GRAY + "Iris" + C.IRIS + "]" + C.GRAY + ": " + msg); - } - - @Nullable @Override - public BiomeProvider getDefaultBiomeProvider(@NotNull String worldName, @Nullable String id) { - return generatorResolver.resolveDefaultBiomeProvider(worldName, id, () -> super.getDefaultBiomeProvider(worldName, id)); - } - - @Nullable - @Override - public ChunkGenerator getDefaultWorldGenerator(@NotNull String worldName, @Nullable String id) { - return generatorResolver.resolveDefaultWorldGenerator(worldName, id); + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + return runtime.getDefaultWorldGenerator(worldName, id); } public ChunkGenerator requireWorldGenerator(String worldName, String id) { - return generatorResolver.requireWorldGenerator(worldName, id); - } - - public WorldRefusalReporter worldRefusals() { - return generatorResolver.refusals(); - } - - public void splash() { - Iris.info("Custom Biomes: " + INMS.get().countCustomBiomes()); - printPacks(); - - IrisSafeguard.mode().trySplash(); - } - - private void printPacks() { - File packFolder = Iris.service(StudioSVC.class).getWorkspaceFolder(); - IrisSplashComposer.composePackLines(packFolder, Iris::reportError).thenAccept(lines -> { - if (isEnabled()) { - lines.forEach(Iris::info); - } - }); - } - - public int getIrisVersion() { - String input = getDescription().getVersion(); - int hyphenIndex = input.indexOf('-'); - String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex); - if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) { - return -1; - } - try { - return Integer.parseInt(release.replace(".", "")); - } catch (NumberFormatException invalid) { - return -1; - } - } - - public int getMCVersion() { - try { - String version = Bukkit.getVersion(); - Matcher matcher = Pattern.compile("\\(MC: ([\\d.]+)\\)").matcher(version); - if (matcher.find()) { - version = matcher.group(1).replaceAll("\\.", ""); - long versionNumber = Long.parseLong(version); - if (versionNumber > Integer.MAX_VALUE) { - return -1; - } - return (int) versionNumber; - } - return -1; - } catch (Exception e) { - return -1; - } + return runtime.requireWorldGenerator(worldName, id); } } diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrap.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrap.java index 642b0d235..076cbcdfe 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrap.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrap.java @@ -1,233 +1,12 @@ package art.arcane.iris; -import art.arcane.iris.world.lifecycle.BukkitStartupPaths; -import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration; -import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry; -import art.arcane.iris.world.lifecycle.HuskWorldQuarantine; -import art.arcane.iris.world.lifecycle.MissingWorldStorageLog; -import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap; -import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker; -import art.arcane.iris.pack.DefaultPackBootstrapProvisioner; -import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest; -import art.arcane.iris.pack.datapack.DataVersion; -import io.papermc.paper.ServerBuildInfo; -import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult; -import art.arcane.iris.platform.bootstrap.SlimJar; -import art.arcane.iris.world.safeguard.GenerationRefusalNotice; import io.papermc.paper.plugin.bootstrap.BootstrapContext; import io.papermc.paper.plugin.bootstrap.PluginBootstrap; -import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent; -import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType; -import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; @SuppressWarnings("UnstableApiUsage") public final class IrisBootstrap implements PluginBootstrap { @Override public void bootstrap(BootstrapContext context) { - WorldReplacementBootstrapMarker.markBootstrapped(); - try { - loadRuntimeLibraries(context); - BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent(); - reconcilePendingWorldReplacements(context, startupPaths); - quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message)); - requireUsableWorldStorage(startupPaths); - ProvisionResult provisioned = provision(context, startupPaths); - Path datapackRoot = provisioned.datapackRoot(); - context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot); - } catch (Throwable failure) { - armStartupFailure(context, failure); - } - } - - private static void loadRuntimeLibraries(BootstrapContext context) { - SlimJar.loadBootstrap( - context.getDataDirectory().resolve("cache").resolve("libraries"), - ServerBuildInfo.buildInfo().minecraftVersionId(), - new SlimJar.BootstrapLogger() { - @Override - public void info(String message) { - context.getLogger().info(message); - } - - @Override - public void error(String message) { - context.getLogger().error(message); - } - - @Override - public void debug(String message) { - context.getLogger().debug(message); - } - }); - } - - private static void reconcilePendingWorldReplacements( - BootstrapContext context, - BukkitStartupPaths startupPaths - ) { - try { - WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile( - context.getDataDirectory(), - startupPaths.levelRoot(), - startupPaths.bukkitConfiguration(), - message -> context.getLogger().info(message) - ); - if (result.transactions() > 0) { - context.getLogger().info( - "Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained", - result.transactions(), - result.published(), - result.rolledBack(), - result.retained() - ); - } - } catch (IOException failure) { - throw new IllegalStateException( - "Unable to reconcile pending Iris world replacements before registry bootstrap", - failure - ); - } - } - - /** - * Moves a hot-deleted world's husk out of {@code /dimensions/iris} before anything enumerates - * it. - *

- * Deleting a loaded world's folder and letting the server save the level back leaves a directory holding - * only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is - * classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from - * the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes - * no console input and hangs startup forever. The folder is moved rather than deleted, so it stays - * recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless. - */ - static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer warn) { - HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn); - } - - /** - * Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from. - *

- * The server enumerates levels from {@code /dimensions//} on disk, so a world - * whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world - * it cannot generate with a fail-closed generator, which stops startup at that world's own level creation, - * after the levels before it have loaded. A pack snapshot that has gone missing is found here instead, - * before any level is created, exactly as a corrupt {@code dimensions/.json} is. An Iris world in a - * vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it - * with the vanilla generator without ever asking Iris. - *

- * A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and - * its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither - * is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has - * already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder, - * or a move that failed) owns nothing to lose. Both are only reported here. - */ - static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException { - Path levelRoot = startupPaths.levelRoot(); - Path levelName = levelRoot.getFileName(); - if (levelName == null || levelName.toString().isBlank()) { - throw new IOException("Configured level root has no startup level id: " + levelRoot); - } - List entries = BukkitWorldConfiguration.auditIrisWorldStorage( - startupPaths.bukkitConfiguration().toFile(), - levelName.toString(), - levelRoot - ); - StringBuilder unusable = new StringBuilder(); - StringBuilder unbound = new StringBuilder(); - for (IrisWorldStorageEntry entry : entries) { - switch (entry.state()) { - case PRESENT -> { - } - case MISSING -> MissingWorldStorageLog.warnOnce( - entry.configuredWorldName(), - entry.storagePath()); - case EMPTY -> MissingWorldStorageLog.warnEmptyOnce( - entry.configuredWorldName(), - entry.storagePath()); - case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ") - .append(entry.configuredWorldName()) - .append(" (") - .append(entry.storagePath()) - .append(": ") - .append(entry.detail() == null ? "storage is unusable" : entry.detail()) - .append(')'); - case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ") - .append(entry.configuredWorldName()) - .append(" (") - .append(entry.storagePath()) - .append("): set worlds.") - .append(entry.configuredWorldName()) - .append(".generator to Iris: in bukkit.yml, or move the folder aside to start a new" - + " vanilla world there"); - } - } - List refusals = new ArrayList<>(2); - if (!unusable.isEmpty()) { - refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: " - + unusable + ". Restore each world folder from a backup, or move it aside; a world with no" - + " folder is reported and skipped, and the server starts."); - } - if (!unbound.isEmpty()) { - refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla" - + " terrain into them: " + unbound + "."); - } - if (!refusals.isEmpty()) { - throw new IllegalStateException(String.join(" ", refusals)); - } - } - - static void armStartupFailure(BootstrapContext context, Throwable failure) { - armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY); - } - - static void armStartupFailure( - BootstrapContext context, - Throwable failure, - LifecycleEventType eventType - ) { - context.getLifecycleManager().registerEventHandler(eventType, event -> { - throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure); - }); - List notice = startupRefusalNotice(failure); - try { - for (String line : notice) { - context.getLogger().error(line); - } - context.getLogger().warn("Iris bootstrap failure", failure); - } catch (Throwable loggingFailure) { - notice.forEach(System.err::println); - failure.addSuppressed(loggingFailure); - failure.printStackTrace(System.err); - } - } - - static List startupRefusalNotice(Throwable failure) { - return GenerationRefusalNotice.compose( - "Iris stopped server startup before any world loads", - GenerationRefusalNotice.causes(failure), - List.of( - "Startup stops at datapack discovery: no world loads and no chunks are written.", - "Fix the cause, then start the server again. Paper's --safeMode hint does not apply:" - + " Iris worlds must not load without Iris." - )); - } - - private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) { - try { - return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest( - context.getDataDirectory(), - message -> context.getLogger().info(message), - startupPaths, - DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId()) - )); - } catch (IOException e) { - throw new IllegalStateException("Unable to provision the Iris startup datapack", e); - } + IrisPluginRuntime.bootstrap(context); } } diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrapSequence.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrapSequence.java new file mode 100644 index 000000000..ffab2f251 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisBootstrapSequence.java @@ -0,0 +1,234 @@ +package art.arcane.iris; + +import art.arcane.iris.world.lifecycle.BukkitStartupPaths; +import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration; +import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry; +import art.arcane.iris.world.lifecycle.HuskWorldQuarantine; +import art.arcane.iris.world.lifecycle.MissingWorldStorageLog; +import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap; +import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker; +import art.arcane.iris.pack.DefaultPackBootstrapProvisioner; +import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest; +import art.arcane.iris.pack.datapack.DataVersion; +import io.papermc.paper.ServerBuildInfo; +import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult; +import art.arcane.iris.platform.bootstrap.SlimJar; +import art.arcane.iris.world.safeguard.GenerationRefusalNotice; +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent; +import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType; +import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +@SuppressWarnings("UnstableApiUsage") +final class IrisBootstrapSequence { + private IrisBootstrapSequence() { + } + + static void bootstrap(BootstrapContext context) { + WorldReplacementBootstrapMarker.markBootstrapped(); + try { + loadRuntimeLibraries(context); + BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent(); + reconcilePendingWorldReplacements(context, startupPaths); + quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message)); + requireUsableWorldStorage(startupPaths); + ProvisionResult provisioned = provision(context, startupPaths); + Path datapackRoot = provisioned.datapackRoot(); + context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot); + } catch (Throwable failure) { + armStartupFailure(context, failure); + } + } + + private static void loadRuntimeLibraries(BootstrapContext context) { + SlimJar.loadBootstrap( + context.getDataDirectory().resolve("cache").resolve("libraries"), + ServerBuildInfo.buildInfo().minecraftVersionId(), + new SlimJar.BootstrapLogger() { + @Override + public void info(String message) { + context.getLogger().info(message); + } + + @Override + public void error(String message) { + context.getLogger().error(message); + } + + @Override + public void debug(String message) { + context.getLogger().debug(message); + } + }); + } + + private static void reconcilePendingWorldReplacements( + BootstrapContext context, + BukkitStartupPaths startupPaths + ) { + try { + WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile( + context.getDataDirectory(), + startupPaths.levelRoot(), + startupPaths.bukkitConfiguration(), + message -> context.getLogger().info(message) + ); + if (result.transactions() > 0) { + context.getLogger().info( + "Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained", + result.transactions(), + result.published(), + result.rolledBack(), + result.retained() + ); + } + } catch (IOException failure) { + throw new IllegalStateException( + "Unable to reconcile pending Iris world replacements before registry bootstrap", + failure + ); + } + } + + /** + * Moves a hot-deleted world's husk out of {@code /dimensions/iris} before anything enumerates + * it. + *

+ * Deleting a loaded world's folder and letting the server save the level back leaves a directory holding + * only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is + * classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from + * the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes + * no console input and hangs startup forever. The folder is moved rather than deleted, so it stays + * recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless. + */ + static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer warn) { + HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn); + } + + /** + * Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from. + *

+ * The server enumerates levels from {@code /dimensions//} on disk, so a world + * whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world + * it cannot generate with a fail-closed generator, which stops startup at that world's own level creation, + * after the levels before it have loaded. A pack snapshot that has gone missing is found here instead, + * before any level is created, exactly as a corrupt {@code dimensions/.json} is. An Iris world in a + * vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it + * with the vanilla generator without ever asking Iris. + *

+ * A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and + * its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither + * is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has + * already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder, + * or a move that failed) owns nothing to lose. Both are only reported here. + */ + static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException { + Path levelRoot = startupPaths.levelRoot(); + Path levelName = levelRoot.getFileName(); + if (levelName == null || levelName.toString().isBlank()) { + throw new IOException("Configured level root has no startup level id: " + levelRoot); + } + List entries = BukkitWorldConfiguration.auditIrisWorldStorage( + startupPaths.bukkitConfiguration().toFile(), + levelName.toString(), + levelRoot + ); + StringBuilder unusable = new StringBuilder(); + StringBuilder unbound = new StringBuilder(); + for (IrisWorldStorageEntry entry : entries) { + switch (entry.state()) { + case PRESENT -> { + } + case MISSING -> MissingWorldStorageLog.warnOnce( + entry.configuredWorldName(), + entry.storagePath()); + case EMPTY -> MissingWorldStorageLog.warnEmptyOnce( + entry.configuredWorldName(), + entry.storagePath()); + case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ") + .append(entry.configuredWorldName()) + .append(" (") + .append(entry.storagePath()) + .append(": ") + .append(entry.detail() == null ? "storage is unusable" : entry.detail()) + .append(')'); + case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ") + .append(entry.configuredWorldName()) + .append(" (") + .append(entry.storagePath()) + .append("): set worlds.") + .append(entry.configuredWorldName()) + .append(".generator to Iris: in bukkit.yml, or move the folder aside to start a new" + + " vanilla world there"); + } + } + List refusals = new ArrayList<>(2); + if (!unusable.isEmpty()) { + refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: " + + unusable + ". Restore each world folder from a backup, or move it aside; a world with no" + + " folder is reported and skipped, and the server starts."); + } + if (!unbound.isEmpty()) { + refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla" + + " terrain into them: " + unbound + "."); + } + if (!refusals.isEmpty()) { + throw new IllegalStateException(String.join(" ", refusals)); + } + } + + static void armStartupFailure(BootstrapContext context, Throwable failure) { + armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY); + } + + static void armStartupFailure( + BootstrapContext context, + Throwable failure, + LifecycleEventType eventType + ) { + context.getLifecycleManager().registerEventHandler(eventType, event -> { + throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure); + }); + List notice = startupRefusalNotice(failure); + try { + for (String line : notice) { + context.getLogger().error(line); + } + context.getLogger().warn("Iris bootstrap failure", failure); + } catch (Throwable loggingFailure) { + notice.forEach(System.err::println); + failure.addSuppressed(loggingFailure); + failure.printStackTrace(System.err); + } + } + + static List startupRefusalNotice(Throwable failure) { + return GenerationRefusalNotice.compose( + "Iris stopped server startup before any world loads", + GenerationRefusalNotice.causes(failure), + List.of( + "Startup stops at datapack discovery: no world loads and no chunks are written.", + "Fix the cause, then start the server again. Paper's --safeMode hint does not apply:" + + " Iris worlds must not load without Iris." + )); + } + + private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) { + try { + return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest( + context.getDataDirectory(), + message -> context.getLogger().info(message), + startupPaths, + DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId()) + )); + } catch (IOException e) { + throw new IllegalStateException("Unable to provision the Iris startup datapack", e); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisPluginRuntime.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisPluginRuntime.java new file mode 100644 index 000000000..902e311ff --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisPluginRuntime.java @@ -0,0 +1,119 @@ +package art.arcane.iris; + +import art.arcane.iris.platform.bukkit.plugin.VolmitSender; +import art.arcane.volmlib.integration.ReloadAware; +import art.arcane.volmlib.util.function.NastyRunnable; +import io.papermc.paper.plugin.bootstrap.BootstrapContext; +import org.bukkit.command.CommandSender; +import org.bukkit.event.Event; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.generator.BiomeProvider; +import org.bukkit.generator.ChunkGenerator; + +import java.util.List; +import java.util.concurrent.CompletionStage; + +interface IrisPluginRuntime { + static IrisPluginRuntime create(Iris plugin) { + return new IrisRuntime(plugin); + } + + static void bootstrap(BootstrapContext context) { + IrisBootstrapSequence.bootstrap(context); + } + + static VolmitSender getSender() { + return IrisRuntime.getSender(); + } + + static T service(Class type) { + return IrisRuntime.service(type); + } + + static void callEvent(Event event) { + IrisRuntime.callEvent(event); + } + + static void msg(String message) { + IrisRuntime.msg(message); + } + + static void warn(String format, Object... args) { + IrisRuntime.warn(format, args); + } + + static void error(String format, Object... args) { + IrisRuntime.error(format, args); + } + + static void debug(String message) { + IrisRuntime.debug(message); + } + + static void debug(String category, int line, String message) { + IrisRuntime.debug(category, line, message); + } + + static void verbose(String message) { + IrisRuntime.verbose(message); + } + + static void success(String message) { + IrisRuntime.success(message); + } + + static void info(String format, Object... args) { + IrisRuntime.info(format, args); + } + + static void later(NastyRunnable task) { + IrisRuntime.later(task); + } + + static void reportErrorChunk(int x, int z, Throwable failure, String extra) { + IrisRuntime.reportErrorChunk(x, z, failure, extra); + } + + static void reportError(Throwable failure) { + IrisRuntime.reportError(failure); + } + + static void reportError(String context, Throwable failure) { + IrisRuntime.reportError(context, failure); + } + + static void dump() { + IrisRuntime.dump(); + } + + static void panic() { + IrisRuntime.panic(); + } + + static String tag(String subTag) { + return IrisRuntime.tag(subTag); + } + + void initialize(); + + void onEnable(); + + void onDisable(); + + CompletionStage commitReload(ReloadAware.PreUnloadReason reason); + + void selectLanguage(CommandSender sender, String[] arguments); + + List completeLanguage(CommandSender sender, String[] arguments); + + void onPlaceholderApiEnable(PluginEnableEvent event); + + void onPlaceholderApiDisable(PluginDisableEvent event); + + BiomeProvider getDefaultBiomeProvider(String worldName, String id); + + ChunkGenerator getDefaultWorldGenerator(String worldName, String id); + + ChunkGenerator requireWorldGenerator(String worldName, String id); +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java new file mode 100644 index 000000000..a05a08af4 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java @@ -0,0 +1,1499 @@ +/* + * Iris is a World Generator for Minecraft Bukkit Servers + * Copyright (c) 2022 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; + +import art.arcane.iris.api.terrain.IrisTerrainService; +import art.arcane.iris.command.CommandSVC; +import art.arcane.iris.configuration.IrisSettings; +import art.arcane.iris.configuration.SettingsHotloadWatch; +import art.arcane.iris.diagnostics.LogFilterSVC; +import art.arcane.iris.diagnostics.splash.IrisSplashComposer; +import art.arcane.iris.generation.concurrent.MultiBurst; +import art.arcane.iris.generation.decoration.tree.TreeBlockMaterial; +import art.arcane.iris.generation.runtime.BlockEditAccess; +import art.arcane.iris.generation.runtime.EngineComponentCleanup; +import art.arcane.iris.generation.runtime.EngineEffectsProvider; +import art.arcane.iris.generation.runtime.EnginePanic; +import art.arcane.iris.generation.runtime.EnginePlatformHooks; +import art.arcane.iris.generation.runtime.EngineWorldManagerProvider; +import art.arcane.iris.generation.runtime.GlobalCacheSVC; +import art.arcane.iris.generation.runtime.IrisEngineEffects; +import art.arcane.iris.generation.runtime.IrisEngineSVC; +import art.arcane.iris.generation.runtime.IrisWorldManager; +import art.arcane.iris.generation.runtime.PreservationRegistry; +import art.arcane.iris.generation.runtime.PreservationSVC; +import art.arcane.iris.generation.simd.SimdSupport; +import art.arcane.iris.integration.ExternalDataSVC; +import art.arcane.iris.integration.IrisIntegrationService; +import art.arcane.iris.integration.IrisPapiInstaller; +import art.arcane.iris.integration.IrisPapiListener; +import art.arcane.iris.integration.IrisPapiState; +import art.arcane.iris.integration.MultiverseCoreLink; +import art.arcane.iris.integration.MultiverseSVC; +import art.arcane.iris.localization.C; +import art.arcane.iris.localization.IrisLanguage; +import art.arcane.iris.pack.datapack.DatapackIngestService; +import art.arcane.iris.pack.datapack.DatapackIngestService.StartupValidationOutcome; +import art.arcane.iris.pack.datapack.DatapackStructureScopeSVC; +import art.arcane.iris.pack.datapack.ServerConfigurator; +import art.arcane.iris.pack.validation.IrisCompat; +import art.arcane.iris.platform.agent.Agent; +import art.arcane.iris.platform.agent.AttachSignal; +import art.arcane.iris.platform.bootstrap.Bindings; +import art.arcane.iris.platform.bootstrap.ServerProperties; +import art.arcane.iris.platform.bootstrap.SlimJar; +import art.arcane.iris.platform.bukkit.BoardSVC; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.platform.bukkit.api.IrisApiEventSVC; +import art.arcane.iris.platform.bukkit.api.IrisTerrainSVC; +import art.arcane.iris.platform.bukkit.chunk.ChunkTickets; +import art.arcane.iris.platform.bukkit.nms.INMS; +import art.arcane.iris.platform.bukkit.plugin.IrisService; +import art.arcane.iris.platform.bukkit.plugin.VolmitSender; +import art.arcane.iris.platform.generation.PlatformChunkGenerator; +import art.arcane.iris.platform.protocol.IrisProtocolService; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.spi.LogLevel; +import art.arcane.iris.studio.StudioSVC; +import art.arcane.iris.studio.edit.EditSVC; +import art.arcane.iris.studio.jigsaw.JigsawStudioService; +import art.arcane.iris.studio.object.ObjectSVC; +import art.arcane.iris.studio.object.ObjectStudioSaveService; +import art.arcane.iris.studio.view.BukkitGuiHost; +import art.arcane.iris.studio.view.GuiHost; +import art.arcane.iris.studio.view.PregeneratorJob; +import art.arcane.iris.studio.wand.WandSVC; +import art.arcane.iris.update.IrisUpdateNotifier; +import art.arcane.iris.world.BukkitWorldReconciler; +import art.arcane.iris.world.IrisStartupAdmissionListener; +import art.arcane.iris.world.IrisStartupValidation; +import art.arcane.iris.world.IrisToolbelt; +import art.arcane.iris.world.IrisWorldGeneratorResolver; +import art.arcane.iris.world.PendingWorldDeleteQueue; +import art.arcane.iris.world.PendingWorldReplacementManager; +import art.arcane.iris.world.entity.EntityRiseSVC; +import art.arcane.iris.world.lifecycle.IrisRuntimeStatics; +import art.arcane.iris.world.lifecycle.ManagedWorldLoader; +import art.arcane.iris.world.lifecycle.MissingWorldStorageLog; +import art.arcane.iris.world.lifecycle.PaperLibBootstrap; +import art.arcane.iris.world.runtime.BukkitEnginePlatformHooks; +import art.arcane.iris.world.runtime.WorldDeletionQueue; +import art.arcane.iris.world.safeguard.IrisSafeguard; +import art.arcane.iris.world.safeguard.RuntimeLockNotice; +import art.arcane.iris.world.task.J; +import art.arcane.iris.world.tree.TreeFellerSVC; +import art.arcane.iris.world.tree.TreeSVC; +import art.arcane.volmlib.integration.ReloadAware; +import art.arcane.volmlib.nativelib.terrain.ServerShutdownBoundary; +import art.arcane.volmlib.util.bukkit.papi.PlaceholderRegistration; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.diagnostics.BukkitDebugDump; +import art.arcane.volmlib.util.director.help.DirectorMiniMenu; +import art.arcane.volmlib.util.exceptions.IrisException; +import art.arcane.volmlib.util.function.NastyRunnable; +import art.arcane.volmlib.util.hud.HudActionBar; +import art.arcane.volmlib.util.hud.HudBossBarLane; +import art.arcane.volmlib.util.io.IO; +import art.arcane.volmlib.util.io.InstanceState; +import art.arcane.volmlib.util.localization.BukkitLanguageSwitcher; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.plugin.ComponentLog; +import art.arcane.volmlib.util.plugin.ComponentText; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.server.PluginDisableEvent; +import org.bukkit.event.server.PluginEnableEvent; +import org.bukkit.generator.BiomeProvider; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.IllegalPluginAccessException; + +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +public final class IrisRuntime implements IrisPluginRuntime { + private static final long SERVER_SHUTDOWN_BOUNDARY_TIMEOUT_SECONDS = 300L; + private static final PrintStream SHUTDOWN_ERRORS = new PrintStream(new FileOutputStream(FileDescriptor.err), true); + private static final long SERVER_STOP_PREGEN_TIMEOUT_MILLIS = 30000L; + + static { + System.setProperty("iris.cache.fast", "true"); + } + + private static VolmitSender sender; + private static Thread shutdownHook; + private static final StackWalker DEBUG_STACK_WALKER = StackWalker.getInstance(); + private static final Set DEBUG_FORWARDERS = Set.of( + Iris.class.getName(), IrisPluginRuntime.class.getName(), IrisRuntime.class.getName()); + static { + try { + InstanceState.updateInstanceId(); + } catch (Throwable ex) { + IrisLogging.reportError("Failed to update the Iris instance id.", ex); + } + } + + private static final Object TEARDOWN_LOCK = new Object(); + private final AtomicBoolean alreadyDrained = new AtomicBoolean(false); + private final AtomicBoolean postStopFinisherStarted = new AtomicBoolean(false); + private final AtomicBoolean serverStopTeardownDeferred = new AtomicBoolean(false); + private final AtomicBoolean servicesDisabled = new AtomicBoolean(false); + private final AtomicBoolean runtimeTeardownFailed = new AtomicBoolean(false); + private final AtomicBoolean sharedRuntimeClosed = new AtomicBoolean(false); + private final AtomicBoolean startupBoundaryRestart = new AtomicBoolean(false); + private final AtomicBoolean terminalCleanupCompleted = new AtomicBoolean(false); + private volatile boolean generatorDrainCompleted; + private volatile boolean enableFailed; + private volatile PlaceholderRegistration papiRegistration; + private volatile IrisPapiListener papiListener; + private volatile IrisPapiState papiState; + private volatile boolean papiLifecycleActive; + private KMap, IrisService> services; + // Copy-on-write: mutated on the main thread during enable() and iterated by the JVM + // shutdown-hook thread during teardown; a plain list would CME and abort the teardown. + private final List enabledServices = new CopyOnWriteArrayList<>(); + private final List deferredShutdownGenerators = new CopyOnWriteArrayList<>(); + private final Iris plugin; + private final IrisWorldGeneratorResolver generatorResolver; + private final BukkitWorldReconciler worldReconciler; + private final PendingWorldDeleteQueue pendingWorldDeletes; + private final PendingWorldReplacementManager pendingWorldReplacements; + private BukkitLanguageSwitcher languageSwitcher; + private IrisUpdateNotifier updateNotifier; + private BukkitDebugDump debugDump; + private volatile SettingsHotloadWatch settingsHotloadWatch; + private volatile ServerShutdownBoundary serverShutdownBoundary; + private boolean shutdownProtectionInitialized; + private ChunkTickets tickets; + + IrisRuntime(Iris plugin) { + this.plugin = plugin; + generatorResolver = new IrisWorldGeneratorResolver(plugin); + worldReconciler = new BukkitWorldReconciler(generatorResolver); + pendingWorldDeletes = new PendingWorldDeleteQueue(plugin); + pendingWorldReplacements = new PendingWorldReplacementManager(plugin); + } + + public static IrisRuntime require() { + IrisRuntime runtime = current(); + if (runtime == null) { + throw new IllegalStateException("Iris is disabled; its runtime is unavailable"); + } + return runtime; + } + + private static IrisRuntime current() { + Iris plugin = Iris.instance; + return plugin == null ? null : (IrisRuntime) plugin.runtime(); + } + + @Override + public void initialize() { + Iris.instance = plugin; + BukkitPlatform.hostPlugin(plugin); + BukkitPlatform.hostConsoleSender(IrisRuntime::getSender); + BukkitPlatform.hostBridge(new BukkitPlatform.HostBridge( + IrisRuntime::bridgeLog, + IrisRuntime::msg, + IrisRuntime::reportError, + (event) -> callEvent((Event) event), + plugin::getDataFolder, + plugin::getDataFile, + plugin::getJarFile, + () -> irisVersion(plugin.getDescription().getVersion()), + IrisRuntime::minecraftVersion)); + SlimJar.load(); + restoreAttachSignal(); + } + + static VolmitSender getSender() { + VolmitSender current = sender; + if (current == null) { + Iris plugin = Iris.instance; + current = new VolmitSender(Bukkit.getConsoleSender()); + current.setTag(plugin == null ? IrisSafeguard.mode().tag("") : plugin.getTag()); + sender = current; + } + return current; + } + + @SuppressWarnings("unchecked") + static T service(Class c) { + IrisRuntime runtime = current(); + if (runtime == null || runtime.services == null) { + throw new IllegalStateException("Iris is disabled; " + c.getSimpleName() + " is unavailable"); + } + return (T) runtime.services.get(c); + } + + static void callEvent(Event e) { + Runnable dispatcher = () -> { + try { + Bukkit.getPluginManager().callEvent(e); + } catch (Throwable ex) { + Iris.reportError("Event dispatch failed for \"" + e.getEventName() + "\".", ex); + if (ex instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (ex instanceof Error error) { + throw error; + } + throw new IllegalStateException(ex); + } + }; + if (!e.isAsynchronous()) { + J.s(dispatcher); + } else { + dispatcher.run(); + } + } + + static boolean isConcreteImplementation(Class candidate, Class requiredType) { + int modifiers = candidate.getModifiers(); + return requiredType.isAssignableFrom(candidate) + && !candidate.isInterface() + && !Modifier.isAbstract(modifiers); + } + + static void msg(String string) { + try { + Iris plugin = Iris.instance; + ComponentLog.logMarkup( + plugin, + Logger.getLogger("Iris"), + logPrefix(plugin), + Level.INFO, + string, + null); + } catch (Throwable e) { + try { + Iris plugin = Iris.instance; + String plainPrefix = ComponentText.legacy(logPrefix(plugin)).plain(); + Logger.getLogger("Iris").log(Level.INFO, plainPrefix + IrisLogging.clean(string)); + } catch (Throwable inner) { + System.err.println("[Iris] Failed to emit log message: " + inner.getMessage()); + inner.printStackTrace(System.err); + } + } + } + + /** + * A warning raised here is the same kind of thing as one raised in core, so it takes the same route: the + * plugin logger at WARNING, where a log scan of logs/latest.log finds it. + */ + static void warn(String format, Object... objs) { + diagnostic(Level.WARNING, safeFormat(format, objs)); + } + + static void error(String format, Object... objs) { + diagnostic(Level.SEVERE, safeFormat(format, objs)); + } + + static void debug(String string) { + if (!IrisSettings.get().getGeneral().isDebug()) { + return; + } + + StackWalker.StackFrame frame; + try { + frame = DEBUG_STACK_WALKER.walk(stream -> stream.dropWhile(IrisRuntime::isDebugForwarder) + .findFirst().orElse(null)); + } catch (Throwable unavailable) { + frame = null; + } + + if (frame == null) { + Iris.debug("Origin", -1, string); + return; + } + + String className = frame.getClassName(); + String[] cc = className == null ? new String[0] : className.split("\\Q.\\E"); + int line = frame.getLineNumber(); + + if (cc.length > 5) { + Iris.debug(cc[3] + "/" + cc[4] + "/" + cc[cc.length - 1], line, string); + return; + } + + if (cc.length > 4) { + Iris.debug(cc[3] + "/" + cc[4], line, string); + return; + } + + if (cc.length > 0) { + Iris.debug(cc[cc.length - 1], line, string); + return; + } + + Iris.debug("Origin", line, string); + } + + private static boolean isDebugForwarder(StackWalker.StackFrame frame) { + String method = frame.getMethodName(); + return DEBUG_FORWARDERS.contains(frame.getClassName()) && (method.equals("debug") || method.equals("verbose")); + } + + static void debug(String category, int line, String string) { + if (!IrisSettings.get().getGeneral().isDebug()) { + return; + } + if (IrisSettings.get().getGeneral().isUseConsoleCustomColors()) { + Iris.msg("" + category + " <#bf3b76>" + line + " " + C.LIGHT_PURPLE + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); + } else { + Iris.msg(C.BLUE + category + ":" + C.AQUA + line + C.RESET + C.LIGHT_PURPLE + " " + string.replaceAll("\\Q<\\E", "[").replaceAll("\\Q>\\E", "]")); + + } + } + + static void verbose(String string) { + Iris.debug(string); + } + + static void success(String string) { + Iris.msg(C.IRIS + string); + } + + static void info(String format, Object... args) { + Iris.msg(C.WHITE + safeFormat(format, args)); + } + + private static String safeFormat(String format, Object... args) { + return IrisLogging.format(format, args); + } + + static void later(NastyRunnable object) { + try { + J.a(() -> { + try { + object.run(); + } catch (Throwable e) { + Iris.reportError(e); + } + }, RNG.r.i(100, 1200)); + } catch (IllegalPluginAccessException ex) { + Iris.verbose("Skipping deferred task registration because plugin access is unavailable: " + + ex.getClass().getSimpleName() + + (ex.getMessage() == null ? "" : " - " + ex.getMessage())); + } + } + + static void reportErrorChunk(int x, int z, Throwable e, String extra) { + if (IrisSettings.get().getGeneral().isDebug()) { + File f = Iris.instance.getDataFile("debug", "chunk-errors", "chunk." + x + "." + z + ".txt"); + + if (!f.exists()) { + J.attempt(() -> { + PrintWriter pw = new PrintWriter(f); + pw.println("Thread: " + Thread.currentThread().getName()); + pw.println("First: " + new Date(M.ms())); + e.printStackTrace(pw); + pw.close(); + }); + } + + Iris.debug("Chunk " + x + "," + z + " Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); + } + } + + static void reportError(Throwable e) { + if (e == null) { + return; + } + IrisRuntime runtime = current(); + if (runtime != null && runtime.serverStopTeardownDeferred.get()) { + e.printStackTrace(SHUTDOWN_ERRORS); + return; + } + + Iris plugin = Iris.instance; + boolean debug = false; + if (plugin != null) { + try { + IrisSettings currentSettings = IrisSettings.settings != null ? IrisSettings.settings : IrisSettings.get(); + debug = currentSettings != null && currentSettings.getGeneral().isDebug(); + } catch (Throwable unreadable) { + debug = false; + } + } + + if (debug) { + String n = e.getClass().getName(); + StackTraceElement[] trace = e.getStackTrace(); + if (trace.length > 0) { + n += "-" + trace[0].getClassName() + "-" + trace[0].getLineNumber(); + } + + if (e.getCause() != null) { + StackTraceElement[] causeTrace = e.getCause().getStackTrace(); + n += "-" + (causeTrace.length == 0 ? e.getCause().getClass().getName() + : causeTrace[0].getClassName() + "-" + causeTrace[0].getLineNumber()); + } + + File f = plugin.getDataFile("debug", "caught-exceptions", n + ".txt"); + + if (!f.exists()) { + J.attempt(() -> { + PrintWriter pw = new PrintWriter(f); + pw.println("Thread: " + Thread.currentThread().getName()); + pw.println("First: " + new Date(M.ms())); + e.printStackTrace(pw); + pw.close(); + }); + } + + Iris.debug("Exception Logged: " + e.getClass().getSimpleName() + ": " + C.RESET + "" + C.LIGHT_PURPLE + e.getMessage()); + } + + e.printStackTrace(System.err); + } + + static void reportError(String context, Throwable e) { + Throwable error = e == null ? new IllegalStateException("Unknown Iris failure") : e; + String message = context == null || context.isBlank() ? "Unhandled Iris failure." : context; + IrisRuntime runtime = current(); + if (runtime != null && runtime.serverStopTeardownDeferred.get()) { + SHUTDOWN_ERRORS.println("[Iris] " + message); + error.printStackTrace(SHUTDOWN_ERRORS); + return; + } + + try { + if (Iris.instance != null) { + Iris.error(message); + } else { + System.err.println("[Iris] " + message); + } + } catch (Throwable inner) { + System.err.println("[Iris] " + message); + inner.printStackTrace(System.err); + } + + Iris.reportError(error); + } + + static void dump() { + try { + File fi = Iris.instance.getDataFile("dump", "td-" + new java.sql.Date(M.ms()) + ".txt"); + FileOutputStream fos = new FileOutputStream(fi); + Map f = Thread.getAllStackTraces(); + PrintWriter pw = new PrintWriter(fos); + for (Thread i : f.keySet()) { + pw.println("========================================"); + pw.println("Thread: '" + i.getName() + "' ID: " + i.threadId() + " STATUS: " + i.getState().name()); + + for (StackTraceElement j : f.get(i)) { + pw.println(" @ " + j.toString()); + } + + pw.println("========================================"); + pw.println(); + pw.println(); + } + pw.println("[%%__USER__%%,%%__RESOURCE__%%,%%__PRODUCT__%%,%%__BUILTBYBIT__%%]"); + + pw.close(); + Iris.info("DUMPED! See " + fi.getAbsolutePath()); + } catch (Throwable e) { + Iris.reportError("Failed to write the Iris thread dump.", e); + } + } + + static void panic() { + EnginePanic.panic(); + } + + static String tag(String subTag) { + return IrisSafeguard.mode().tag(subTag); + } + + private static void restoreAttachSignal() { + try { + if (AttachSignal.restoreJvmHandler()) { + Iris.info("Restored the JVM SIGQUIT handler that the server console replaced"); + } + } catch (RuntimeException failure) { + Iris.reportError("Could not restore the JVM SIGQUIT handler; the Iris agent may fail to attach.", failure); + } + } + + private static void bridgeLog(LogLevel level, String message) { + LogLevel target = level == null ? LogLevel.INFO : level; + Level diagnostic = diagnosticLevel(target); + if (diagnostic != null) { + diagnostic(diagnostic, message); + return; + } + if (target == LogLevel.DEBUG) { + Iris.debug(message); + return; + } + Iris.info(message); + } + + /** + * The java.util.logging level a message keeps, or null when it belongs on the console sender path. + *

+ * Core states a severity and every other adapter honours it; on Bukkit a coloured line through the + * console sender reaches the terminal but not the instance's logs/latest.log, so a WARN-level scan of + * that file never saw a single core warning. Diagnostics go to the plugin logger at their own level + * instead, and NOTICE carries the handful of lifecycle lines that have to land there too. Player-facing + * text still goes through {@code IrisLogging.msg}. + */ + static Level diagnosticLevel(LogLevel level) { + return switch (level) { + case NOTICE -> Level.INFO; + case WARN -> Level.WARNING; + case ERROR -> Level.SEVERE; + case DEBUG, INFO -> null; + }; + } + + private static void diagnostic(Level level, String message) { + String line = IrisLogging.clean(message); + Iris plugin = Iris.instance; + ComponentLog.log( + plugin, + Logger.getLogger("Iris"), + logPrefix(plugin), + level, + ComponentText.literal(line), + null); + } + + private static String logPrefix(Iris plugin) { + return plugin == null ? ComponentLog.discriminator("Iris", "&a") : plugin.getTag(); + } + + static int irisVersion(String input) { + int hyphenIndex = input.indexOf('-'); + String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex); + if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) { + return -1; + } + try { + return Integer.parseInt(release.replace(".", "")); + } catch (NumberFormatException invalid) { + return -1; + } + } + + static int minecraftVersion() { + try { + String version = Bukkit.getVersion(); + Matcher matcher = Pattern.compile("\\(MC: ([\\d.]+)\\)").matcher(version); + if (matcher.find()) { + version = matcher.group(1).replaceAll("\\.", ""); + long versionNumber = Long.parseLong(version); + if (versionNumber > Integer.MAX_VALUE) { + return -1; + } + return (int) versionNumber; + } + return -1; + } catch (Exception e) { + return -1; + } + } + + private void enable() { + EnableTimings timings = new EnableTimings(); + alreadyDrained.set(false); + postStopFinisherStarted.set(false); + serverStopTeardownDeferred.set(false); + servicesDisabled.set(false); + runtimeTeardownFailed.set(false); + sharedRuntimeClosed.set(false); + startupBoundaryRestart.set(false); + terminalCleanupCompleted.set(false); + generatorDrainCompleted = false; + deferredShutdownGenerators.clear(); + MultiBurst.burst.reopen(); + MultiBurst.hydrology.reopen(); + MultiBurst.ioBurst.reopen(); + IrisLanguage.initialize(); + debugDump = BukkitDebugDump.create(plugin, new BukkitDebugDump.Options( + () -> true, + () -> IrisSafeguard::debugReport)); + languageSwitcher = BukkitLanguageSwitcher.register(plugin, IrisLanguage.selections(), + new BukkitLanguageSwitcher.Options("iris", "iris.all", + DirectorMiniMenu.Theme.irisGreen(), IrisLanguage.directorResolver(), IrisLanguage.editorOptions())); + updateNotifier = new IrisUpdateNotifier(plugin); + PaperLibBootstrap.install(); + SimdSupport.install(); + timings.mark("bootstrap"); + services = new KMap<>(); + BukkitPlatform.hostHud(new HudActionBar(plugin), new HudBossBarLane()); + // Explicit, ordered service list: the previous reflective jar scan gave hash-ordered + // enable/disable and paid a full-jar class sweep at boot. Infrastructure first, + // engine/world services next, commands last. + List orderedServices = List.of( + new PreservationSVC(), + new GlobalCacheSVC(), + new LogFilterSVC(), + new ExternalDataSVC(), + new EditSVC(), + new ObjectSVC(), + new ObjectStudioSaveService(), + new JigsawStudioService(), + new StudioSVC(), + new DatapackStructureScopeSVC(), + new IrisEngineSVC(), + new IrisTerrainSVC(), + new TreeSVC(), + new TreeFellerSVC(), + new EntityRiseSVC(), + new WandSVC(), + new BoardSVC(), + new IrisIntegrationService(), + new MultiverseSVC(), + new IrisProtocolService(), + new IrisApiEventSVC(), + new CommandSVC() + ); + for (IrisService i : orderedServices) { + Class serviceType = i.getClass().asSubclass(IrisService.class); + services.put(serviceType, i); + IrisServices.register(serviceType, i); + } + IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class)); + IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class)); + IrisCompat compat = IrisCompat.configured(plugin.getDataFile("compat.json")); + IrisServices.register(IrisCompat.class, compat); + timings.mark("services"); + ServerConfigurator.configure(); + timings.mark("serverConfig"); + StartupValidationOutcome datapackValidation = DatapackIngestService.validateOnStartup(); + timings.mark("datapacks"); + IrisSafeguard.execute(); + timings.mark("safeguard"); + getSender().setTag(plugin.getTag()); + // A cosmetic banner must never abort the bootstrap. + J.attempt(this::splash); + IrisSafeguard.printReports(); + IrisSafeguard.printFooter(); + // Paper's bootstrap runs before any plugin logger exists, so orphan-storage warnings raised there + // never reach logs/latest.log. Replay them once now that the platform log is up. + MissingWorldStorageLog.replayToPlatformLog(); + timings.mark("splash"); + tickets = new ChunkTickets(); + MultiverseCoreLink multiverseCoreLink = new MultiverseCoreLink(); + IrisServices.register(MultiverseCoreLink.class, multiverseCoreLink); + IrisServices.register(EngineComponentCleanup.class, (EngineComponentCleanup) BukkitPlatform::unregisterListener); + IrisServices.register(EngineEffectsProvider.class, (EngineEffectsProvider) IrisEngineEffects::new); + IrisServices.register(EnginePlatformHooks.class, new BukkitEnginePlatformHooks()); + IrisServices.register(EngineWorldManagerProvider.class, + (EngineWorldManagerProvider) IrisWorldManager::new); + IrisServices.register(WorldDeletionQueue.class, pendingWorldDeletes); + IrisServices.register(ManagedWorldLoader.class, (ManagedWorldLoader) this::loadManagedWorld); + SettingsHotloadWatch watch = new SettingsHotloadWatch(plugin.getDataFile("iris.json")); + settingsHotloadWatch = watch; + StudioSVC.gateDownloadsOnStaleTempCleanup(MultiBurst.ioBurst.completeValueAsync(() -> { + IO.delete(getTemp()); + return null; + })); + timings.mark("tempSweep"); + // One throwing service must not abort the bootstrap: the steps after this loop + // (listeners, shutdown hook, replacement journals) are the safety-critical ones. + // Only services that actually enabled get listeners and a later onDisable. + enabledServices.clear(); + for (IrisService service : orderedServices) { + long serviceStartedAt = System.nanoTime(); + try { + service.onEnable(); + enabledServices.add(service); + timings.markService(service.getClass().getSimpleName(), serviceStartedAt); + } catch (Throwable e) { + // A service failure is NOT a datapack validation failure: the admission gate + // must never lock every login over a broken cosmetic service. Log loudly, + // continue degraded, and clean up whatever the partial onEnable started + // (a failed service is excluded from the teardown loop). + Iris.reportError("Failed to enable " + service.getClass().getSimpleName() + "; continuing with a degraded runtime.", e); + try { + service.onDisable(); + } catch (Throwable cleanup) { + Iris.reportError("Failed to clean up partially enabled " + service.getClass().getSimpleName() + ".", cleanup); + } + } + } + for (IrisService service : enabledServices) { + try { + plugin.registerListener(service); + } catch (Throwable e) { + Iris.reportError("Failed to register listener for " + service.getClass().getSimpleName() + ".", e); + } + } + timings.mark("serviceEnable"); + if (datapackValidation == StartupValidationOutcome.READY) { + IrisServices.get(ExternalDataSVC.class).setContentChangeListener(generatorResolver::requestExternalContentRefresh); + generatorResolver.validateAllPacks(); + } + timings.mark("packValidation"); + addShutdownHook(); + pendingWorldReplacements.processPendingStartupReplacements(); + pendingWorldDeletes.processPendingStartupWorldDeletes(); + + if (J.isFolia() && IrisStartupValidation.isReady()) { + J.s(this::reconcileStartupWorlds, 1); + } + + J.s(() -> { + pendingWorldReplacements.captureVanillaLevelContext(); + pendingWorldReplacements.verifyLoadedPublishedWorlds(); + J.a(this::bstats); + J.ar(watch::checkConfigHotload, 10); + J.s(this::setupPapi); + if (IrisStartupValidation.isReady()) { + J.a(DatapackIngestService::runPostStartupTasks, 60); + autoStartStudio(); + } + if (!J.isFolia() && IrisStartupValidation.isReady()) { + reconcileStartupWorlds(); + } + IrisToolbelt.retainMantleDataForSlice(String.class.getCanonicalName()); + // The mantle stores block values as NativeBlockState, so a BlockData retention can never + // match a slice type; the block-state slice is deliberately never retainable (regenerable, huge). + IrisToolbelt.retainMantleDataForSlice(TreeBlockMaterial.class.getCanonicalName()); + }); + timings.mark("startupTasks"); + timings.report(); + } + + private static final class EnableTimings { + private static final int REPORTED_SERVICES = 3; + + private final long startedAt = System.nanoTime(); + private final StringBuilder phases = new StringBuilder(); + private final Map serviceMillis = new LinkedHashMap<>(); + private long lastMark = startedAt; + + private void mark(String phase) { + long now = System.nanoTime(); + if (!phases.isEmpty()) { + phases.append(' '); + } + phases.append(phase).append('=').append(TimeUnit.NANOSECONDS.toMillis(now - lastMark)).append("ms"); + lastMark = now; + } + + private void markService(String service, long serviceStartedAt) { + serviceMillis.put(service, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - serviceStartedAt)); + } + + private void report() { + IrisLogging.notice("Enabled in %dms (%s)", + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt), phases); + String slowest = serviceMillis.entrySet().stream() + .sorted(Map.Entry.comparingByValue().reversed()) + .limit(REPORTED_SERVICES) + .map(entry -> entry.getKey() + "=" + entry.getValue() + "ms") + .collect(Collectors.joining(" ")); + if (!slowest.isBlank()) { + IrisLogging.notice("Slowest services: %s", slowest); + } + } + } + + private File getTemp() { + return plugin.getDataFolder("cache", "temp"); + } + + private void reconcileStartupWorlds() { + generatorResolver.startupWorldsReady().whenComplete((ignored, failure) -> { + if (failure != null) { + Iris.reportError("Could not resume Iris startup world reconciliation.", failure); + return; + } + J.s(() -> worldReconciler.checkForBukkitWorlds(s -> true)); + }); + } + + private void addShutdownHook() { + removeShutdownHook(); + serverShutdownBoundary = INMS.isBound() ? INMS.get().createServerShutdownBoundary() : null; + shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook"); + try { + Runtime.getRuntime().addShutdownHook(shutdownHook); + } catch (IllegalStateException ex) { + Iris.debug("Skipping shutdown hook registration because JVM shutdown is already in progress."); + } + } + + /** + * The static-field guard in addShutdownHook is dead across a plugin reload (fresh + * classloader, fresh static), so onDisable must deregister the hook explicitly or each + * reload stacks another hook pinning the previous plugin classloader for the JVM's life. + */ + private void removeShutdownHook() { + Thread hook = shutdownHook; + shutdownHook = null; + if (hook == null) { + return; + } + try { + Runtime.getRuntime().removeShutdownHook(hook); + } catch (IllegalStateException ignored) { + Iris.debug("Skipping shutdown hook removal because JVM shutdown is already in progress."); + } + } + + public BukkitWorldReconciler worldReconciler() { + return worldReconciler; + } + + /** + * The load every integration goes through. {@code /iris load} and the Multiverse guard both land here, + * so a world loaded from outside Iris still gets the keyed creator, the pack's environment and the + * bukkit.yml reconciliation that make it an Iris world rather than a vanilla one under the same name. + */ + private CompletableFuture loadManagedWorld(String configuredWorldName) { + return worldReconciler.loadWorld(ServerProperties.BUKKIT_YML, configuredWorldName) + .thenApply(this::managedWorldLoadResult); + } + + private ManagedWorldLoader.ManagedWorldLoad managedWorldLoadResult(BukkitWorldReconciler.LoadResult result) { + if (!result.succeeded() && result.failure() != null) { + Iris.reportError("Could not explicitly load Iris world " + result.worldKey() + ": " + result.message(), result.failure()); + } + return new ManagedWorldLoader.ManagedWorldLoad(result.succeeded(), result.message()); + } + + public PendingWorldReplacementManager pendingWorldReplacements() { + return pendingWorldReplacements; + } + + public BukkitDebugDump debugDump() { + return debugDump; + } + + public ChunkTickets tickets() { + return tickets; + } + + private void autoStartStudio() { + if (IrisSettings.get().getStudio().isAutoStartDefaultStudio()) { + Iris.debug("Starting up auto Studio!"); + try { + Player r = new KList<>(plugin.getServer().getOnlinePlayers()).getRandom(); + Iris.service(StudioSVC.class).open(r != null ? new VolmitSender(r) : getSender(), 1337, IrisSettings.get().getGenerator().getDefaultWorldType(), (w) -> { + J.s(() -> { + final Location spawn = w.getSpawnLocation(); + for (Player i : plugin.getServer().getOnlinePlayers()) { + final Runnable playerTask = () -> { + i.setGameMode(GameMode.SPECTATOR); + BukkitPlatform.teleportAsync(i, spawn); + }; + if (!J.runEntity(i, playerTask)) { + playerTask.run(); + } + } + }); + }); + } catch (IrisException e) { + Iris.reportError(e); + } + } + } + + @Override + public void onEnable() { + enableFailed = false; + shutdownProtectionInitialized = false; + IrisStartupValidation.begin(); + Bukkit.getPluginManager().registerEvents(new IrisStartupAdmissionListener(), plugin); + try { + generatorResolver.refusals().attach(plugin); + IrisPlatforms.bind(new BukkitPlatform()); + Bukkit.getPluginManager().registerEvents(pendingWorldReplacements, plugin); + pendingWorldReplacements.registerPlatformEntryListener(); + if (!INMS.isBound()) { + refuseUnsupportedServer(); + return; + } + initializeShutdownProtection(); + enable(); + } catch (Throwable failure) { + enableFailed = true; + if (!FailedEnableLock.engage(failure, FailedEnableLock.irisWorldsPresent(), + generatorResolver.refusals().startupWorldsCreated())) { + throw failure; + } + return; + } + BukkitGuiHost.install(); + // super.onEnable() already registers this instance as a listener. + plugin.enablePlugin(); + if (IrisStartupValidation.isRestartRequired()) { + String restartReason = IrisStartupValidation.denialReason() + .orElse("Iris startup validation requires a restart."); + startupBoundaryRestart.set(true); + ServerConfigurator.restartAtStartupBoundary(restartReason); + return; + } + papiLifecycleActive = true; + setupPapi(); + reportLockedRuntime(); + } + + private void initializeShutdownProtection() { + if (!INMS.get().supportsIrisWorldGeneration()) { + return; + } + if (!Agent.install()) { + throw new IllegalStateException("Iris Java agent is unavailable; shutdown protection cannot be installed."); + } + INMS.get().initializeLifecycle(plugin.getClass().getClassLoader()); + shutdownProtectionInitialized = true; + } + + private void refuseUnsupportedServer() { + Throwable bindFailure = INMS.bindFailure(); + IllegalStateException failure = new IllegalStateException("Iris cannot start: " + (bindFailure == null + ? "no NMS binding is available for this server version." + : bindFailure.getMessage()), bindFailure); + if (FailedEnableLock.engage(failure, FailedEnableLock.irisWorldsPresent(), + generatorResolver.refusals().startupWorldsCreated())) { + enableFailed = true; + return; + } + Iris.error(failure.getMessage()); + // Deferred one tick: disablePlugin from inside onEnable re-enters onDisable + // synchronously and the loader then continues registering the half-enabled plugin. + J.s(() -> Bukkit.getPluginManager().disablePlugin(plugin), 1); + } + + private static void reportLockedRuntime() { + String denial = IrisStartupValidation.denialReason().orElse(null); + if (denial == null) { + return; + } + for (String line : RuntimeLockNotice.compose(denial, FailedEnableLock.irisWorldsPresent())) { + Iris.error(line); + } + } + + @Override + public void selectLanguage(CommandSender sender, String[] arguments) { + BukkitLanguageSwitcher current = languageSwitcher; + if (current != null) { + current.command(sender, arguments); + } + } + + @Override + public List completeLanguage(CommandSender sender, String[] arguments) { + BukkitLanguageSwitcher current = languageSwitcher; + return current == null ? List.of() : current.complete(sender, arguments); + } + + @Override + public void onDisable() { + pendingWorldReplacements.awaitStagingForShutdown(); + GuiHost.shutdown(); + preservePendingBlockDrops(); + papiLifecycleActive = false; + if (updateNotifier != null) { + updateNotifier.close(); + updateNotifier = null; + } + if (debugDump != null) { + debugDump.close(); + debugDump = null; + } + if (languageSwitcher != null) { + languageSwitcher.close(); + languageSwitcher = null; + } + IrisLanguage.shutdown(); + teardownPapi(); + boolean deferToServerStop = FailedEnableLock.defersTeardownToServerStop(enableFailed, IrisToolbelt.isServerStopping()) + && tryDeferPluginClassLoaderClose(); + boolean restartingAtStartupBoundary = startupBoundaryRestart.get(); + if (restartingAtStartupBoundary) { + teardownRuntime("startup-boundary-restart", 30L); + } else if (deferToServerStop) { + quiesceRuntimeForServerShutdown("onDisable"); + startPostStopFinisher(); + } else { + teardownRuntime("onDisable", 30L); + removeShutdownHook(); + } + if (BukkitPlatform.hasHud()) { + BukkitPlatform.hudBar().shutdown(); + BukkitPlatform.hudLanes().shutdown(); + } + SettingsHotloadWatch activeSettingsHotloadWatch = settingsHotloadWatch; + settingsHotloadWatch = null; + if (activeSettingsHotloadWatch != null) { + activeSettingsHotloadWatch.close(); + } + // super.onDisable() cancels plugin tasks and unregisters every listener. + plugin.disablePlugin(); + if (!deferToServerStop || restartingAtStartupBoundary) { + finishTerminalCleanup(); + } + } + + @Override + public CompletionStage commitReload(ReloadAware.PreUnloadReason reason) { + preservePendingBlockDrops(); + papiLifecycleActive = false; + teardownPapi(); + if (IrisToolbelt.isServerStopping() && tryDeferPluginClassLoaderClose()) { + quiesceRuntimeForServerShutdown("pre-unload:" + reason); + startPostStopFinisher(); + Iris.debug("Pre-unload hook deferred generator teardown until Paper closes its chunk schedulers."); + return CompletableFuture.completedFuture(null); + } + if (alreadyDrained.get()) { + Iris.debug("Pre-unload hook skipped; Iris already drained."); + return CompletableFuture.completedFuture(null); + } + Iris.debug("BileTools pre-unload hook fired (" + reason + "). Freezing all Iris worlds."); + drainOnce("pre-unload:" + reason, 45L); + return CompletableFuture.completedFuture(null); + } + + private boolean tryDeferPluginClassLoaderClose() { + if (!shutdownProtectionInitialized) { + return false; + } + try { + INMS.get().deferPluginClassLoaderClose(); + return true; + } catch (RuntimeException | LinkageError failure) { + Iris.reportError("Failed to retain the Iris plugin class loader; draining shutdown inline.", failure); + return false; + } + } + + /** + * Drains the world generators exactly once. Serialized against the JVM shutdown hook so a + * second caller cannot rip the pools or services out from under an in-flight drain. + */ + private void drainOnce(String reason, long timeoutSeconds) { + synchronized (TEARDOWN_LOCK) { + if (alreadyDrained.compareAndSet(false, true)) { + drainWorldGenerators(reason, timeoutSeconds); + } + } + } + + /** + * Full teardown: generators, then services, then the shared pools and the service map. + * Both onDisable and the JVM shutdown hook route through here; whichever runs second is a no-op. + */ + private void teardownRuntime(String reason, long timeoutSeconds) { + synchronized (TEARDOWN_LOCK) { + if (alreadyDrained.compareAndSet(false, true)) { + drainWorldGenerators(reason, timeoutSeconds); + } + + if (serverStopTeardownDeferred.get() && !generatorDrainCompleted) { + return; + } + + if (services != null && servicesDisabled.compareAndSet(false, true)) { + // Only services whose onEnable actually completed; disabling a service that + // never initialized runs teardown against uninitialized state. + for (IrisService service : enabledServices) { + try { + service.onDisable(); + } catch (Throwable e) { + runtimeTeardownFailed.set(true); + Iris.reportError("Failed to disable " + service.getClass().getSimpleName() + ".", e); + } + } + } + + if (!sharedRuntimeClosed.compareAndSet(false, true)) { + return; + } + + try { + MultiBurst.burst.close(); + } catch (Throwable failure) { + Iris.reportError("Failed to close Iris generation workers.", failure); + } + try { + MultiBurst.hydrology.close(); + } catch (Throwable failure) { + Iris.reportError("Failed to close Iris hydrology workers.", failure); + } + try { + MultiBurst.ioBurst.close(); + } catch (Throwable failure) { + Iris.reportError("Failed to close Iris I/O workers.", failure); + } + IrisRuntimeStatics.reset(); + releaseStatics(); + } + } + + private void releaseStatics() { + tickets = null; + sender = null; + Iris.instance = null; + } + + private void quiesceRuntimeForServerShutdown(String reason) { + serverStopTeardownDeferred.set(true); + JigsawStudioService jigsawStudioService = IrisServices.getOrNull(JigsawStudioService.class); + if (jigsawStudioService != null) { + try { + jigsawStudioService.quiesceForServerShutdown(); + } catch (Throwable e) { + Iris.reportError("Failed to quiesce Jigsaw Studio before server shutdown.", e); + } + } + StudioSVC studioService = IrisServices.getOrNull(StudioSVC.class); + if (studioService != null) { + studioService.quiesceDownloadsForShutdown(); + } + + try { + if (J.isFolia()) { + PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS); + } else { + List worlds = Bukkit.getWorlds(); + PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS, () -> { + for (World world : worlds) { + INMS.get().pollChunkTask(world); + } + }); + } + } catch (Throwable e) { + Iris.reportError("Failed to quiesce the Iris pregenerator before server shutdown.", e); + } + + for (World world : Bukkit.getWorlds()) { + PlatformChunkGenerator generator = IrisToolbelt.access(world); + if (generator == null) { + continue; + } + IrisToolbelt.beginWorldMaintenance(world, reason); + if (!deferredShutdownGenerators.contains(generator)) { + deferredShutdownGenerators.add(generator); + } + generator.quiesceForServerShutdown(); + } + } + + private void startPostStopFinisher() { + if (!postStopFinisherStarted.compareAndSet(false, true)) { + return; + } + Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"), + "Iris-PostStop-Finisher"); + finisher.setDaemon(false); + finisher.start(); + } + + private void runShutdownHook() { + if (startupBoundaryRestart.get()) { + finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L); + return; + } + finishRuntimeAfterServerShutdown("shutdown-hook"); + } + + private void finishRuntimeAfterServerShutdown(String reason) { + if (!awaitServerShutdownBoundary()) { + SHUTDOWN_ERRORS.println("[Iris] The server did not reach its post-world-close boundary; retaining the runtime and plugin class loader until JVM exit."); + return; + } + finishDeferredRuntimeTeardown(reason, 30L); + } + + private boolean awaitServerShutdownBoundary() { + ServerShutdownBoundary boundary = serverShutdownBoundary; + if (boundary == null) { + return false; + } + try { + return boundary.await( + SERVER_SHUTDOWN_BOUNDARY_TIMEOUT_SECONDS, + TimeUnit.SECONDS + ); + } catch (Throwable e) { + SHUTDOWN_ERRORS.println("[Iris] Failed to await Paper's post-world-close shutdown boundary."); + e.printStackTrace(SHUTDOWN_ERRORS); + return false; + } + } + + private void finishDeferredRuntimeTeardown(String reason, long timeoutSeconds) { + teardownRuntime(reason, timeoutSeconds); + if (serverStopTeardownDeferred.get() && !generatorDrainCompleted) { + SHUTDOWN_ERRORS.println("[Iris] Runtime cleanup is incomplete; retaining services, pools and the plugin class loader until JVM exit."); + return; + } + finishTerminalCleanup(); + } + + private void finishTerminalCleanup() { + if (!terminalCleanupCompleted.compareAndSet(false, true)) { + return; + } + try { + if (INMS.isBound()) { + INMS.get().uninjectBukkit(); + } + } catch (Throwable failure) { + Iris.reportError("Failed to remove Iris world-generation hooks.", failure); + } + try { + plugin.runPostShutdown(); + } catch (Throwable e) { + runtimeTeardownFailed.set(true); + Iris.reportError("Failed to run Iris post-shutdown cleanup.", e); + } finally { + boolean activeResources = serverStopTeardownDeferred.get() + && (runtimeTeardownFailed.get() || hasActiveShutdownResources()); + IrisPlatforms.unbind(); + BukkitPlatform.releaseHost(); + if (activeResources) { + SHUTDOWN_ERRORS.println("[Iris] Owned background work has not completed cleanup; retaining the plugin class loader until JVM exit."); + } else { + try { + if (shutdownProtectionInitialized) { + INMS.get().releasePluginClassLoaderClose(); + } else { + SlimJar.closeNativeProviders(); + } + } catch (Throwable failure) { + SHUTDOWN_ERRORS.println("[Iris] Failed to release the plugin class loader after runtime cleanup."); + failure.printStackTrace(SHUTDOWN_ERRORS); + } + } + } + } + + private boolean hasActiveShutdownResources() { + if (!MultiBurst.burst.isTerminated() || !MultiBurst.hydrology.isTerminated() + || !MultiBurst.ioBurst.isTerminated()) { + return true; + } + return services != null + && services.get(PreservationSVC.class) instanceof PreservationSVC preservation + && preservation.hasActiveResources(); + } + + private void preservePendingBlockDrops() { + for (World world : Bukkit.getWorlds()) { + PlatformChunkGenerator generator = IrisToolbelt.access(world); + if (generator != null && generator.getEngine() != null + && generator.getEngine().getWorldManager() instanceof IrisWorldManager manager) { + manager.flushPendingBlockDropsAsync().whenComplete((ignored, failure) -> { + if (failure != null) { + Iris.reportError("Failed to preserve pending block loot before Iris teardown.", failure); + } + }); + } + } + } + + private void drainWorldGenerators(String reason, long timeoutSeconds) { + List irisWorlds = new ArrayList<>(); + List generators = new ArrayList<>(); + if (serverStopTeardownDeferred.get()) { + generators.addAll(deferredShutdownGenerators); + } else { + for (World world : Bukkit.getWorlds()) { + PlatformChunkGenerator generator = IrisToolbelt.access(world); + if (generator != null) { + irisWorlds.add(world); + generators.add(generator); + } + } + } + if (generators.isEmpty()) { + generatorDrainCompleted = true; + Iris.debug("No Iris worlds to freeze."); + return; + } + + for (World world : irisWorlds) { + IrisToolbelt.beginWorldMaintenance(world, reason, true); + } + + J.attempt(PregeneratorJob::shutdownInstance); + + List> closes = new ArrayList<>(); + for (PlatformChunkGenerator generator : generators) { + try { + closes.add(generator.closeAsync()); + } catch (Throwable t) { + Iris.reportError(t); + } + } + + if (closes.isEmpty()) return; + + try { + CompletableFuture.allOf(closes.toArray(new CompletableFuture[0])) + .get(timeoutSeconds, TimeUnit.SECONDS); + generatorDrainCompleted = closes.size() == generators.size(); + if (generatorDrainCompleted) { + Iris.debug("All Iris chunk generators parked. Safe to unload."); + } + } catch (TimeoutException e) { + Iris.reportError("Iris generator drain timed out after " + timeoutSeconds + "s.", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + Iris.reportError("Iris generator drain was interrupted.", e); + } catch (ExecutionException e) { + Iris.reportError(e.getCause() == null ? e : e.getCause()); + } + } + + @Override + public void onPlaceholderApiEnable(PluginEnableEvent event) { + if ("PlaceholderAPI".equals(event.getPlugin().getName())) { + setupPapi(); + } + } + + @Override + public void onPlaceholderApiDisable(PluginDisableEvent event) { + if ("PlaceholderAPI".equals(event.getPlugin().getName())) { + teardownPapi(); + } + } + + private synchronized void setupPapi() { + if (!papiLifecycleActive || papiRegistration != null + || !PlaceholderRegistration.isPlaceholderApiEnabled()) { + return; + } + + IrisPapiState state = new IrisPapiState(() -> IrisServices.getOrNull(IrisTerrainService.class)); + PlaceholderRegistration registration = new PlaceholderRegistration(plugin.getLogger()); + + if (!IrisPapiInstaller.install(registration, state, plugin.getLogger())) { + return; + } + + IrisPapiListener listener = new IrisPapiListener(state); + + try { + Bukkit.getPluginManager().registerEvents(listener, plugin); + } catch (Throwable failure) { + registration.unregister(); + Iris.warn("Failed to attach the Iris PlaceholderAPI listener: " + + failure.getClass().getName() + ": " + failure.getMessage()); + return; + } + + papiState = state; + papiListener = listener; + papiRegistration = registration; + } + + private synchronized void teardownPapi() { + IrisPapiListener listener = papiListener; + papiListener = null; + + if (listener != null) { + HandlerList.unregisterAll(listener); + } + + PlaceholderRegistration registration = papiRegistration; + papiRegistration = null; + + if (registration != null) { + registration.unregister(); + } + + IrisPapiState state = papiState; + papiState = null; + + if (state != null) { + state.clear(); + } + } + + private void bstats() { + if (IrisSettings.get().getGeneral().isMetrics()) { + Bindings.setupBstats(plugin); + } + } + + @Override + public BiomeProvider getDefaultBiomeProvider(String worldName, String id) { + return generatorResolver.resolveDefaultBiomeProvider(worldName, id, () -> null); + } + + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + return generatorResolver.resolveDefaultWorldGenerator(worldName, id); + } + + @Override + public ChunkGenerator requireWorldGenerator(String worldName, String id) { + return generatorResolver.requireWorldGenerator(worldName, id); + } + + private void splash() { + Iris.info("Custom Biomes: " + INMS.get().countCustomBiomes()); + printPacks(); + + IrisSafeguard.mode().trySplash(); + } + + private void printPacks() { + File packFolder = Iris.service(StudioSVC.class).getWorkspaceFolder(); + IrisSplashComposer.composePackLines(packFolder, Iris::reportError).thenAccept(lines -> { + if (plugin.isEnabled()) { + lines.forEach(Iris::info); + } + }); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDebug.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDebug.java index 662c4ef3c..891a4401f 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDebug.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandDebug.java @@ -1,6 +1,7 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; import art.arcane.iris.configuration.IrisSettings; import art.arcane.iris.localization.BukkitCommandMessagesExtended; import art.arcane.iris.localization.IrisLanguage; @@ -19,7 +20,7 @@ public final class CommandDebug implements DirectorExecutor { @Param(name = "upload", defaultValue = "true", description = "Upload the report to mclo.gs", descriptionKey = "iris.director.commandiris.param.debugdump_upload") boolean upload, @Param(name = "sender", contextual = true) CommandSender sender ) { - Iris.instance.debugDump().request(sender, upload); + IrisRuntime.require().debugDump().request(sender, upload); } @Director(sync = true, description = "Print version information", descriptionKey = "iris.director.commandiris.director.print_version_information") diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandIris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandIris.java index 1c09dfd01..d615ab0c0 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandIris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/command/CommandIris.java @@ -19,6 +19,7 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; import art.arcane.iris.world.BukkitWorldReconciler; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.configuration.IrisSettings; @@ -216,7 +217,7 @@ public class CommandIris implements DirectorExecutor { ) { NamespacedKey worldKey; try { - worldKey = Iris.instance.pendingWorldReplacements().resolveRequestedWorldKey(target); + worldKey = IrisRuntime.require().pendingWorldReplacements().resolveRequestedWorldKey(target); } catch (IllegalArgumentException e) { sender().sendMessage(C.RED + e.getMessage()); return; @@ -240,7 +241,7 @@ public class CommandIris implements DirectorExecutor { } try { - PendingWorldReplacementManager.StagedReplacement staged = Iris.instance + PendingWorldReplacementManager.StagedReplacement staged = IrisRuntime.require() .pendingWorldReplacements() .stageReplacement(sender(), worldKey, dimension, seed); String seedDetail = seed == null @@ -634,7 +635,7 @@ public class CommandIris implements DirectorExecutor { VolmitSender responseSender = sender(); responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_LOADING_WORLD, MessageArgument.untrusted("logicalWorldName", logicalWorldName))); - Iris.instance.worldReconciler() + IrisRuntime.require().worldReconciler() .loadWorld(BUKKIT_YML, worldKey.toString()) .whenComplete((result, failure) -> { Runnable response = () -> reportLoadWorldResult( diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/studio/wand/WandSVC.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/studio/wand/WandSVC.java index 8e530d127..fd6275ad3 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/studio/wand/WandSVC.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/studio/wand/WandSVC.java @@ -27,6 +27,8 @@ import org.bukkit.Particle; import org.bukkit.Sound; import org.bukkit.World; import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; +import art.arcane.iris.platform.bukkit.chunk.TicketHolder; import art.arcane.iris.localization.IrisLanguage; import art.arcane.iris.localization.RuntimeUiMessages; import art.arcane.iris.studio.edit.DustRevealer; @@ -109,7 +111,7 @@ public class WandSVC implements IrisService { int total = c.getSizeX() * c.getSizeY() * c.getSizeZ(); var latch = new CountDownLatch(1); - var holder = Iris.tickets.getHolder(p.getWorld()); + TicketHolder holder = IrisRuntime.require().tickets().getHolder(p.getWorld()); new Job() { private volatile int i; private Chunk chunk; diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/BukkitWorldReconciler.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/BukkitWorldReconciler.java index dee36913c..e1dd5aee2 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/BukkitWorldReconciler.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/BukkitWorldReconciler.java @@ -68,8 +68,8 @@ public final class BukkitWorldReconciler { private final Backend backend; private final LifecycleOperationCoordinator coordinator; - public BukkitWorldReconciler(Iris plugin) { - this(new BukkitBackend(plugin), LifecycleOperationCoordinator.get()); + public BukkitWorldReconciler(IrisWorldGeneratorResolver generatorResolver) { + this(new BukkitBackend(generatorResolver), LifecycleOperationCoordinator.get()); } BukkitWorldReconciler(Backend backend, LifecycleOperationCoordinator coordinator) { @@ -688,10 +688,10 @@ public final class BukkitWorldReconciler { } private static final class BukkitBackend implements Backend { - private final Iris plugin; + private final IrisWorldGeneratorResolver generatorResolver; - private BukkitBackend(Iris plugin) { - this.plugin = Objects.requireNonNull(plugin, "plugin"); + private BukkitBackend(IrisWorldGeneratorResolver generatorResolver) { + this.generatorResolver = Objects.requireNonNull(generatorResolver, "generatorResolver"); } @Override @@ -734,13 +734,13 @@ public final class BukkitWorldReconciler { try { configuredWorldName = configuredWorldName(worldKey); Iris.info("Loading World: %s | Generator: %s", IrisWorldStorage.logicalName(worldKey), dimension); - generator = plugin.requireWorldGenerator(configuredWorldName, dimension); + generator = generatorResolver.requireWorldGenerator(configuredWorldName, dimension); irisDimension = IrisWorldGeneratorResolver.loadDimension(configuredWorldName, dimension); if (generator == null || irisDimension == null) { throw new IllegalStateException("Could not resolve the Iris generator or dimension \"" + dimension + "\"."); } } catch (Throwable refusal) { - plugin.worldRefusals().report(configuredWorldName, worldKey, refusal); + generatorResolver.refusals().report(configuredWorldName, worldKey, refusal); return CompletableFuture.failedFuture(refusal); } try { diff --git a/adapters/bukkit/plugin/src/test/gameplay/native-lifecycle-fixture/src/art/arcane/iris/fixture/NativeLifecycleFixture.java b/adapters/bukkit/plugin/src/test/gameplay/native-lifecycle-fixture/src/art/arcane/iris/fixture/NativeLifecycleFixture.java index 33dd08149..3587a5fb5 100644 --- a/adapters/bukkit/plugin/src/test/gameplay/native-lifecycle-fixture/src/art/arcane/iris/fixture/NativeLifecycleFixture.java +++ b/adapters/bukkit/plugin/src/test/gameplay/native-lifecycle-fixture/src/art/arcane/iris/fixture/NativeLifecycleFixture.java @@ -1,6 +1,6 @@ package art.arcane.iris.fixture; -import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; import art.arcane.volmlib.nativelib.NativeAdapters; import art.arcane.iris.world.runtime.RuntimeInjection; import art.arcane.iris.generation.runtime.Engine; @@ -138,7 +138,7 @@ public final class NativeLifecycleFixture extends JavaPlugin implements WorldRun return CompletableFuture.completedFuture(null); } if (WorldCreatorCompat.persistentLevelRoot(TREASURE_KEY).exists()) { - return Iris.instance.worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString()); + return IrisRuntime.require().worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString()); } return runAsync(() -> { try { diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/FailedEnableLockTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/FailedEnableLockTest.java index f86195317..3bd213ee6 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/FailedEnableLockTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/FailedEnableLockTest.java @@ -148,16 +148,16 @@ public class FailedEnableLockTest { try (EnableFixture fixture = new EnableFixture(false)) { IllegalStateException failure = assertThrows(IllegalStateException.class, plugin::onEnable); assertTrue(failure.getMessage(), failure.getMessage().contains("already bound")); - Field failed = Iris.class.getDeclaredField("enableFailed"); + Field failed = IrisRuntime.class.getDeclaredField("enableFailed"); failed.setAccessible(true); - assertTrue(failed.getBoolean(plugin)); + assertTrue(failed.getBoolean(plugin.runtime())); } } @Test public void anUnsupportedServerWithIrisWorldsLocksInsteadOfDisablingIris() throws Exception { Iris plugin = plugin(); - set(plugin, "pendingWorldReplacements", mock(PendingWorldReplacementManager.class)); + set(IrisRuntime.class, plugin.runtime(), "pendingWorldReplacements", mock(PendingWorldReplacementManager.class)); try (EnableFixture fixture = new EnableFixture(true); MockedStatic nms = mockStatic(INMS.class); @@ -208,18 +208,18 @@ public class FailedEnableLockTest { /** * Paper builds plugins through its class loader, so the plugin under test is the real class with its fields - * set by hand: the resolver getDefaultWorldGenerator delegates to, and whatever enable touches before failing. + * set by hand: the runtime getDefaultWorldGenerator delegates to, and whatever enable touches before failing. */ private static Iris plugin() throws Exception { Iris plugin = mock(Iris.class, CALLS_REAL_METHODS); - set(plugin, "generatorResolver", new IrisWorldGeneratorResolver(plugin)); + set(Iris.class, plugin, "runtime", new IrisRuntime(plugin)); return plugin; } - private static void set(Iris plugin, String name, Object value) throws Exception { - Field field = Iris.class.getDeclaredField(name); + private static void set(Class owner, Object target, String name, Object value) throws Exception { + Field field = owner.getDeclaredField(name); field.setAccessible(true); - field.set(plugin, value); + field.set(target, value); } /** diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisApiServiceDiscoveryTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisApiServiceDiscoveryTest.java index 21f0656ad..78c406b53 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisApiServiceDiscoveryTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisApiServiceDiscoveryTest.java @@ -11,8 +11,8 @@ import static org.junit.Assert.assertTrue; public class IrisApiServiceDiscoveryTest { @Test public void bothApiServicesSatisfyTheServiceLoaderRule() { - assertTrue(Iris.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class)); - assertTrue(Iris.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class)); + assertTrue(IrisRuntime.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class)); + assertTrue(IrisRuntime.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class)); } @Test diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapFailureContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapFailureContractTest.java index 8e58e530c..28c4d0f8d 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapFailureContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapFailureContractTest.java @@ -31,7 +31,7 @@ public class IrisBootstrapFailureContractTest { when(context.getLogger()).thenReturn(logger); when(context.getLifecycleManager()).thenReturn(manager); - IrisBootstrap.armStartupFailure(context, cause, eventType); + IrisBootstrapSequence.armStartupFailure(context, cause, eventType); assertSame(eventType, manager.eventType); IllegalStateException failure = assertThrows(IllegalStateException.class, manager::runCapturedHandler); @@ -47,7 +47,7 @@ public class IrisBootstrapFailureContractTest { IllegalStateException failure = new IllegalStateException("Iris world storage is unusable", new IOException("Invalid generation manifest: manifest.json")); - IrisBootstrap.armStartupFailure(context, failure, lifecycleEventType()); + IrisBootstrapSequence.armStartupFailure(context, failure, lifecycleEventType()); ArgumentCaptor lines = ArgumentCaptor.forClass(String.class); verify(logger, atLeastOnce()).error(lines.capture()); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapWorldStorageContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapWorldStorageContractTest.java index 78919ab63..811c602c4 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapWorldStorageContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisBootstrapWorldStorageContractTest.java @@ -44,7 +44,7 @@ public class IrisBootstrapWorldStorageContractTest { IllegalStateException failure = assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); assertTrue(failure.getMessage(), failure.getMessage().contains("world_iris_orphan2")); assertTrue(failure.getMessage(), @@ -64,7 +64,7 @@ public class IrisBootstrapWorldStorageContractTest { writeServerProperties(serverRoot); writeBukkitWorlds(serverRoot, "world_iris_husk"); - IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)); + IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)); assertTrue(MissingWorldStorageLog.hasWarned("world_iris_husk")); } @@ -83,8 +83,8 @@ public class IrisBootstrapWorldStorageContractTest { writeBukkitWorlds(serverRoot, "world_iris_husk"); List warnings = new ArrayList<>(); - IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); - IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)); + IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); + IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)); assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk"))); assertEquals(1, warnings.size()); @@ -106,7 +106,7 @@ public class IrisBootstrapWorldStorageContractTest { writeBukkitWorlds(serverRoot); List warnings = new ArrayList<>(); - IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); + IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk"))); assertEquals(1, warnings.size()); @@ -121,13 +121,13 @@ public class IrisBootstrapWorldStorageContractTest { writeBukkitWorlds(serverRoot, "world_iris_kept"); List warnings = new ArrayList<>(); - IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); + IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/kept"))); assertTrue(warnings.isEmpty()); assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); } /** @@ -142,13 +142,13 @@ public class IrisBootstrapWorldStorageContractTest { writeBukkitWorlds(serverRoot, "world_iris_marked"); List warnings = new ArrayList<>(); - IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); + IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add); assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/marked/iris/engine-data"))); assertTrue(warnings.isEmpty()); assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); } @Test @@ -158,7 +158,7 @@ public class IrisBootstrapWorldStorageContractTest { writeServerProperties(serverRoot); writeBukkitWorlds(serverRoot, "world_iris_orphan1"); - IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)); + IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)); assertTrue(MissingWorldStorageLog.hasWarned("world_iris_orphan1")); } @@ -170,7 +170,7 @@ public class IrisBootstrapWorldStorageContractTest { writeServerProperties(serverRoot); writeBukkitWorlds(serverRoot, "world_iris_moon"); - IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)); + IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)); assertFalse(MissingWorldStorageLog.hasWarned("world_iris_moon")); } @@ -190,7 +190,7 @@ public class IrisBootstrapWorldStorageContractTest { IllegalStateException failure = assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); assertTrue(failure.getMessage(), failure.getMessage().contains(serverRoot.toRealPath().resolve("world/dimensions/minecraft/overworld") @@ -210,7 +210,7 @@ public class IrisBootstrapWorldStorageContractTest { IllegalStateException failure = assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); assertTrue(failure.getMessage(), failure.getMessage().contains("Invalid generation manifest")); assertFalse(failure.getMessage(), failure.getMessage().contains("\n")); @@ -229,7 +229,7 @@ public class IrisBootstrapWorldStorageContractTest { IllegalStateException failure = assertThrows( IllegalStateException.class, - () -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot))); + () -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot))); assertTrue(failure.getMessage(), failure.getMessage().contains("worlds.world.generator")); assertTrue(failure.getMessage(), @@ -247,7 +247,7 @@ public class IrisBootstrapWorldStorageContractTest { writeServerProperties(serverRoot); writeBukkitWorlds(serverRoot); - IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)); + IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)); } private static BukkitStartupPaths startupPaths(Path serverRoot) throws Exception { diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticLogLevelTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticLogLevelTest.java index 2cd3c60c5..8eecab987 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticLogLevelTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticLogLevelTest.java @@ -15,18 +15,18 @@ import static org.junit.Assert.assertNull; public class IrisDiagnosticLogLevelTest { @Test public void coreDiagnosticsKeepTheirSeverity() { - assertEquals(Level.WARNING, Iris.diagnosticLevel(LogLevel.WARN)); - assertEquals(Level.SEVERE, Iris.diagnosticLevel(LogLevel.ERROR)); + assertEquals(Level.WARNING, IrisRuntime.diagnosticLevel(LogLevel.WARN)); + assertEquals(Level.SEVERE, IrisRuntime.diagnosticLevel(LogLevel.ERROR)); } @Test public void informationalAndDebugMessagesStayOnTheInformationalPath() { - assertNull(Iris.diagnosticLevel(LogLevel.INFO)); - assertNull(Iris.diagnosticLevel(LogLevel.DEBUG)); + assertNull(IrisRuntime.diagnosticLevel(LogLevel.INFO)); + assertNull(IrisRuntime.diagnosticLevel(LogLevel.DEBUG)); } @Test public void lifecycleNoticesReachThePluginLoggerAtInfo() { - assertEquals(Level.INFO, Iris.diagnosticLevel(LogLevel.NOTICE)); + assertEquals(Level.INFO, IrisRuntime.diagnosticLevel(LogLevel.NOTICE)); } } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticsTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticsTest.java index 84cab8263..a7ef3cd62 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticsTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisDiagnosticsTest.java @@ -23,8 +23,8 @@ public class IrisDiagnosticsTest { public void serviceInitializationSkipsPackageHelperClasses() throws Exception { Class registrar = Class.forName("art.arcane.iris.command.PaperCommandRegistrar"); - assertFalse(Iris.isConcreteImplementation(registrar, IrisService.class)); - assertTrue(Iris.isConcreteImplementation(CommandSVC.class, IrisService.class)); + assertFalse(IrisRuntime.isConcreteImplementation(registrar, IrisService.class)); + assertTrue(IrisRuntime.isConcreteImplementation(CommandSVC.class, IrisService.class)); // The service package is eagerly Class.forName-scanned by JarScanner at enable; a class // referencing Paper-only types there prints an NCDFE stack trace on plain Spigot. assertFalse( diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisErrorReportingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisErrorReportingTest.java index c3dd7e0e5..6a4d21c12 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisErrorReportingTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisErrorReportingTest.java @@ -9,10 +9,8 @@ import org.mockito.MockedStatic; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; -import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -53,9 +51,6 @@ public class IrisErrorReportingTest { IrisSettings previousSettings = IrisSettings.settings; PrintStream previousError = System.err; Iris plugin = mock(Iris.class); - Field deferred = Iris.class.getDeclaredField("serverStopTeardownDeferred"); - deferred.setAccessible(true); - deferred.set(plugin, new AtomicBoolean()); File report = new File(temporaryFolder.getRoot(), "failure.txt"); when(plugin.getDataFile(any(String[].class))).thenReturn(report); ByteArrayOutputStream output = new ByteArrayOutputStream(); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownMaintenanceTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownMaintenanceTest.java index 67e9ffd28..d412eff36 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownMaintenanceTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownMaintenanceTest.java @@ -10,7 +10,6 @@ import art.arcane.iris.platform.bukkit.plugin.IrisService; import art.arcane.iris.platform.bukkit.plugin.VolmitPlugin; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.world.lifecycle.IrisRuntimeStatics; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.iris.generation.runtime.GenerationSessionLease; import art.arcane.iris.generation.runtime.GenerationSessionManager; @@ -38,6 +37,7 @@ import org.mockito.MockedStatic; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; @@ -84,7 +84,7 @@ public class IrisShutdownMaintenanceTest { assertTrue(release.await(5, TimeUnit.SECONDS)); return false; }); - setField(fixture.plugin, "serverShutdownBoundary", boundary); + setField(fixture.runtime, "serverShutdownBoundary", boundary); fixture.quiesce(); fixture.startFinisher(); try { @@ -108,9 +108,9 @@ public class IrisShutdownMaintenanceTest { @Test public void missingShutdownBoundaryDoesNotAuthorizeResourceRelease() throws Exception { try (Fixture fixture = new Fixture()) { - Method method = Iris.class.getDeclaredMethod("awaitServerShutdownBoundary"); + Method method = IrisRuntime.class.getDeclaredMethod("awaitServerShutdownBoundary"); method.setAccessible(true); - assertEquals(false, method.invoke(fixture.plugin)); + assertEquals(false, method.invoke(fixture.runtime)); } } @@ -179,7 +179,7 @@ public class IrisShutdownMaintenanceTest { assertSame(fixture.plugin.getClass().getClassLoader(), invocation.getArgument(0)); return null; }).when(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader()); - invoke(fixture.plugin, "initializeShutdownProtection"); + invoke(fixture.runtime, "initializeShutdownProtection"); verify(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader()); verify(fixture.binding, never()).injectBukkit(); } @@ -190,7 +190,7 @@ public class IrisShutdownMaintenanceTest { try (Fixture fixture = new Fixture(); MockedStatic agent = mockStatic(Agent.class)) { when(fixture.binding.supportsIrisWorldGeneration()).thenReturn(true); InvocationTargetException failure = assertThrows(InvocationTargetException.class, - () -> invoke(fixture.plugin, "initializeShutdownProtection")); + () -> invoke(fixture.runtime, "initializeShutdownProtection")); assertTrue(failure.getCause() instanceof IllegalStateException); verify(fixture.binding, never()).initializeLifecycle(fixture.plugin.getClass().getClassLoader()); } @@ -208,8 +208,8 @@ public class IrisShutdownMaintenanceTest { IllegalStateException failure = new IllegalStateException("world hook teardown failed"); fixture.nms.when(INMS::isBound).thenReturn(true); doThrow(failure).when(fixture.binding).uninjectBukkit(); - setField(fixture.plugin, "services", new KMap, IrisService>()); - setField(fixture.plugin, "enabledServices", List.of(service)); + setField(fixture.runtime, "services", new KMap, IrisService>()); + setField(fixture.runtime, "enabledServices", List.of(service)); doAnswer(invocation -> { platforms.verify(IrisPlatforms::unbind); bukkitPlatform.verify(BukkitPlatform::releaseHost); @@ -257,8 +257,8 @@ public class IrisShutdownMaintenanceTest { IrisService service = mock(IrisService.class); IllegalStateException failure = new IllegalStateException("service teardown failed"); doThrow(failure).when(service).onDisable(); - setField(fixture.plugin, "services", new KMap, IrisService>()); - setField(fixture.plugin, "enabledServices", List.of(service)); + setField(fixture.runtime, "services", new KMap, IrisService>()); + setField(fixture.runtime, "enabledServices", List.of(service)); fixture.quiesce(); fixture.finish(5L); verify(service).onDisable(); @@ -293,7 +293,7 @@ public class IrisShutdownMaintenanceTest { assertTrue(started.await(5, TimeUnit.SECONDS)); IllegalStateException failure = new IllegalStateException("post-shutdown callback failed"); AtomicBoolean cleanupAttempted = new AtomicBoolean(); - KList callbacks = new KList<>(); + List callbacks = new ArrayList<>(); callbacks.add(() -> { throw failure; }); callbacks.add(() -> { cleanupAttempted.set(true); @@ -302,9 +302,7 @@ public class IrisShutdownMaintenanceTest { Field callbacksField = VolmitPlugin.class.getDeclaredField("postShutdown"); callbacksField.setAccessible(true); callbacksField.set(fixture.plugin, callbacks); - Method runCallbacks = VolmitPlugin.class.getDeclaredMethod("runPostShutdown"); - runCallbacks.setAccessible(true); - runCallbacks.invoke(doCallRealMethod().when(fixture.plugin)); + doCallRealMethod().when(fixture.plugin).runPostShutdown(); fixture.quiesce(); fixture.finish(5L); iris.verify(() -> Iris.reportError("Failed to run Iris post-shutdown cleanup.", failure)); @@ -326,8 +324,8 @@ public class IrisShutdownMaintenanceTest { public void incompleteDrainRetainsServicesWorkersAndClassLoader() throws Exception { try (Fixture fixture = new Fixture(); MockedStatic iris = mockStatic(Iris.class)) { IrisService service = mock(IrisService.class); - setField(fixture.plugin, "services", new KMap, IrisService>()); - setField(fixture.plugin, "enabledServices", List.of(service)); + setField(fixture.runtime, "services", new KMap, IrisService>()); + setField(fixture.runtime, "enabledServices", List.of(service)); when(fixture.generator.closeAsync()).thenReturn(new CompletableFuture<>()); fixture.quiesce(); fixture.finish(0L); @@ -340,7 +338,7 @@ public class IrisShutdownMaintenanceTest { @Test public void serverStopPreUnloadDefersTeardownWhileTheClassLoaderIsHeld() throws Exception { try (Fixture fixture = new Fixture()) { - setField(fixture.plugin, "postStopFinisherStarted", new AtomicBoolean(true)); + setField(fixture.runtime, "postStopFinisherStarted", new AtomicBoolean(true)); try { fixture.commitReloadDuringServerStop(); verify(fixture.binding).deferPluginClassLoaderClose(); @@ -373,7 +371,7 @@ public class IrisShutdownMaintenanceTest { @Test public void serverStopPreUnloadDrainsInlineWithoutInitializedProtection() throws Exception { try (Fixture fixture = new Fixture()) { - setField(fixture.plugin, "shutdownProtectionInitialized", false); + setField(fixture.runtime, "shutdownProtectionInitialized", false); try { fixture.commitReloadDuringServerStop(); verify(fixture.binding, never()).deferPluginClassLoaderClose(); @@ -386,20 +384,21 @@ public class IrisShutdownMaintenanceTest { } } - private static void invoke(Iris plugin, String name) throws ReflectiveOperationException { - Method method = Iris.class.getDeclaredMethod(name); + private static void invoke(IrisRuntime runtime, String name) throws ReflectiveOperationException { + Method method = IrisRuntime.class.getDeclaredMethod(name); method.setAccessible(true); - method.invoke(plugin); + method.invoke(runtime); } - private static void setField(Iris plugin, String name, Object value) throws ReflectiveOperationException { - Field field = Iris.class.getDeclaredField(name); + private static void setField(IrisRuntime runtime, String name, Object value) throws ReflectiveOperationException { + Field field = IrisRuntime.class.getDeclaredField(name); field.setAccessible(true); - field.set(plugin, value); + field.set(runtime, value); } private static final class Fixture implements AutoCloseable { private final Iris plugin = mock(Iris.class); + private final IrisRuntime runtime = mock(IrisRuntime.class); private final World world = mock(World.class); private final IrisWorld irisWorld = mock(IrisWorld.class); private final Engine engine = mock(Engine.class); @@ -419,15 +418,16 @@ public class IrisShutdownMaintenanceTest { private Fixture() throws ReflectiveOperationException { IrisSettings.settings = new IrisSettings(); - setField(plugin, "shutdownProtectionInitialized", true); - setField(plugin, "alreadyDrained", new AtomicBoolean()); - setField(plugin, "servicesDisabled", new AtomicBoolean()); - setField(plugin, "runtimeTeardownFailed", new AtomicBoolean()); - setField(plugin, "sharedRuntimeClosed", new AtomicBoolean()); - setField(plugin, "terminalCleanupCompleted", new AtomicBoolean()); - setField(plugin, "serverStopTeardownDeferred", new AtomicBoolean()); - setField(plugin, "postStopFinisherStarted", new AtomicBoolean()); - setField(plugin, "deferredShutdownGenerators", new CopyOnWriteArrayList()); + setField(runtime, "plugin", plugin); + setField(runtime, "shutdownProtectionInitialized", true); + setField(runtime, "alreadyDrained", new AtomicBoolean()); + setField(runtime, "servicesDisabled", new AtomicBoolean()); + setField(runtime, "runtimeTeardownFailed", new AtomicBoolean()); + setField(runtime, "sharedRuntimeClosed", new AtomicBoolean()); + setField(runtime, "terminalCleanupCompleted", new AtomicBoolean()); + setField(runtime, "serverStopTeardownDeferred", new AtomicBoolean()); + setField(runtime, "postStopFinisherStarted", new AtomicBoolean()); + setField(runtime, "deferredShutdownGenerators", new CopyOnWriteArrayList()); when(world.getKey()).thenReturn(NamespacedKey.fromString(identity)); when(engine.getWorld()).thenReturn(irisWorld); when(irisWorld.hasPlatformWorld()).thenReturn(true); @@ -441,42 +441,42 @@ public class IrisShutdownMaintenanceTest { } private void quiesce() throws ReflectiveOperationException { - Method method = Iris.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class); + Method method = IrisRuntime.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class); method.setAccessible(true); - method.invoke(plugin, "server_stop"); + method.invoke(runtime, "server_stop"); quiesces++; } private void drain() throws ReflectiveOperationException { - Method method = Iris.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class); + Method method = IrisRuntime.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class); method.setAccessible(true); - method.invoke(plugin, "manual_disable", 5L); + method.invoke(runtime, "manual_disable", 5L); } private void commitReloadDuringServerStop() throws ReflectiveOperationException { - setField(plugin, "alreadyDrained", new AtomicBoolean()); + setField(runtime, "alreadyDrained", new AtomicBoolean()); toolbelt.when(IrisToolbelt::isServerStopping).thenReturn(true); - doCallRealMethod().when(plugin).commitReload(any()); - plugin.commitReload(ReloadAware.PreUnloadReason.HOT_UNLOAD); + doCallRealMethod().when(runtime).commitReload(any()); + runtime.commitReload(ReloadAware.PreUnloadReason.HOT_UNLOAD); } private boolean serverStopTeardownDeferred() throws ReflectiveOperationException { - Field field = Iris.class.getDeclaredField("serverStopTeardownDeferred"); + Field field = IrisRuntime.class.getDeclaredField("serverStopTeardownDeferred"); field.setAccessible(true); - return ((AtomicBoolean) field.get(plugin)).get(); + return ((AtomicBoolean) field.get(runtime)).get(); } private void finish(long timeoutSeconds) throws ReflectiveOperationException { - Method method = Iris.class.getDeclaredMethod("finishDeferredRuntimeTeardown", String.class, long.class); + Method method = IrisRuntime.class.getDeclaredMethod("finishDeferredRuntimeTeardown", String.class, long.class); method.setAccessible(true); - method.invoke(plugin, "test_shutdown", timeoutSeconds); + method.invoke(runtime, "test_shutdown", timeoutSeconds); } private void startFinisher() throws ReflectiveOperationException { - Method method = Iris.class.getDeclaredMethod("startPostStopFinisher"); + Method method = IrisRuntime.class.getDeclaredMethod("startPostStopFinisher"); method.setAccessible(true); - method.invoke(plugin); + method.invoke(runtime); } @Override diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java index 4e7a9d3f5..4eb6d9368 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java @@ -11,16 +11,13 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -import static org.mockito.Answers.CALLS_REAL_METHODS; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; public class IrisVersionNumberTest { @Test public void releaseAndQualifiedBuildsUseTheSameVersionNumber() { for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) { - assertEquals(version, 433, plugin(version).getIrisVersion()); + assertEquals(version, 433, IrisRuntime.irisVersion(version)); } } @@ -29,10 +26,8 @@ public class IrisVersionNumberTest { try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) { assertNotNull(stream); PluginDescriptionFile description = new PluginDescriptionFile(stream); - Iris plugin = mock(Iris.class, CALLS_REAL_METHODS); - doReturn(description).when(plugin).getDescription(); - assertNotEquals(-1, plugin.getIrisVersion()); + assertNotEquals(-1, IrisRuntime.irisVersion(description.getVersion())); } } @@ -40,28 +35,21 @@ public class IrisVersionNumberTest { public void malformedAndOverflowingReleaseNumbersStayInvalid() { for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test", "2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) { - assertEquals(version, -1, plugin(version).getIrisVersion()); + assertEquals(version, -1, IrisRuntime.irisVersion(version)); } } @Test public void supportedMinecraftVersionsRetainTheirEngineNumbers() { - Iris plugin = mock(Iris.class, CALLS_REAL_METHODS); try (MockedStatic bukkit = mockStatic(Bukkit.class)) { bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-74-ver/26.1.2@e4e17fc (MC: 26.1.2)"); - assertEquals(2612, plugin.getMCVersion()); + assertEquals(2612, IrisRuntime.minecraftVersion()); bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-8-ver/26.1.x@62dc0f2 (MC: 26.1.2)"); - assertEquals(2612, plugin.getMCVersion()); + assertEquals(2612, IrisRuntime.minecraftVersion()); bukkit.when(Bukkit::getVersion).thenReturn("26.2-133 (MC: 26.2)"); - assertEquals(262, plugin.getMCVersion()); + assertEquals(262, IrisRuntime.minecraftVersion()); bukkit.when(Bukkit::getVersion).thenReturn("26.3-169 (MC: 26.3)"); - assertEquals(263, plugin.getMCVersion()); + assertEquals(263, IrisRuntime.minecraftVersion()); } } - - private static Iris plugin(String version) { - Iris plugin = mock(Iris.class, CALLS_REAL_METHODS); - doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription(); - return plugin; - } } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandDebugTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandDebugTest.java index 239424daf..c10765b85 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandDebugTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandDebugTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.command; import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; import art.arcane.iris.command.CommandSVC; import art.arcane.iris.world.task.J; import art.arcane.volmlib.util.diagnostics.BukkitDebugDump; @@ -30,18 +31,18 @@ import static org.mockito.Mockito.when; public class CommandDebugTest { @Test public void nestedDumpPreservesUploadDefaultAndLocalOnlyOption() { - Iris previousPlugin = Iris.instance; - Iris plugin = mock(Iris.class); - Iris.instance = plugin; + IrisRuntime runtime = mock(IrisRuntime.class); BukkitDebugDump dump = mock(BukkitDebugDump.class); CommandSender sender = mock(CommandSender.class); DirectorSender invocationSender = mock(DirectorSender.class); - when(plugin.debugDump()).thenReturn(dump); + when(runtime.debugDump()).thenReturn(dump); when(invocationSender.getName()).thenReturn("Console"); DirectorContextRegistry contexts = new DirectorContextRegistry(); contexts.register(CommandSender.class, (invocation, arguments) -> sender); - try (MockedStatic iris = mockStatic(Iris.class)) { + try (MockedStatic iris = mockStatic(Iris.class); + MockedStatic runtimes = mockStatic(IrisRuntime.class)) { + runtimes.when(IrisRuntime::require).thenReturn(runtime); DirectorRuntimeEngine engine = DirectorEngineFactory.create(new CommandIris(), DirectorEngineOptions.builder().contexts(contexts).build()); @@ -52,8 +53,6 @@ public class CommandDebugTest { assertEquals(List.of("dump", "toggle", "version"), DirectorMiniMenu.resolveHelp(engine, List.of("debug")).orElseThrow().entries().stream() .map(entry -> entry.getDescriptor().getName()).sorted().toList()); - } finally { - Iris.instance = previousPlugin; } } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/integration/IrisPapiLifecycleTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/integration/IrisPapiLifecycleTest.java index 2c87939ea..d4cdcc860 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/integration/IrisPapiLifecycleTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/integration/IrisPapiLifecycleTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.integration; import art.arcane.iris.Iris; +import art.arcane.iris.IrisRuntime; import art.arcane.volmlib.util.bukkit.papi.PlaceholderRegistration; import org.bukkit.Bukkit; import org.bukkit.event.HandlerList; @@ -89,12 +90,21 @@ public class IrisPapiLifecycleTest { when(iris.getLogger()).thenReturn(Logger.getAnonymousLogger()); doCallRealMethod().when(iris).onPlaceholderApiEnable(any()); doCallRealMethod().when(iris).onPlaceholderApiDisable(any()); - Field lifecycle = Iris.class.getDeclaredField("papiLifecycleActive"); - lifecycle.setAccessible(true); - lifecycle.setBoolean(iris, active); + IrisRuntime runtime = mock(IrisRuntime.class); + doCallRealMethod().when(runtime).onPlaceholderApiEnable(any()); + doCallRealMethod().when(runtime).onPlaceholderApiDisable(any()); + set(IrisRuntime.class, runtime, "plugin", iris); + set(IrisRuntime.class, runtime, "papiLifecycleActive", active); + set(Iris.class, iris, "runtime", runtime); return iris; } + private static void set(Class owner, Object target, String name, Object value) throws ReflectiveOperationException { + Field field = owner.getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } + private static Plugin namedPlugin(String name) { Plugin plugin = mock(Plugin.class); when(plugin.getName()).thenReturn(name); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/world/BukkitWorldReconcilerRuntimeTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/world/BukkitWorldReconcilerRuntimeTest.java index abef86a46..564cf1c3e 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/world/BukkitWorldReconcilerRuntimeTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/world/BukkitWorldReconcilerRuntimeTest.java @@ -107,10 +107,10 @@ public class BukkitWorldReconcilerRuntimeTest { public void aRefusedReconcilerCreateIsReportedAsARefusal() throws Exception { NamespacedKey key = new NamespacedKey("iris", "probe"); IllegalStateException refusal = new IllegalStateException("Iris generation history is unusable at /srv/probe."); - Iris plugin = mock(Iris.class); + IrisWorldGeneratorResolver resolver = mock(IrisWorldGeneratorResolver.class); WorldRefusalReporter refusals = mock(WorldRefusalReporter.class); - when(plugin.worldRefusals()).thenReturn(refusals); - when(plugin.requireWorldGenerator("world_iris_probe", "overworld")).thenThrow(refusal); + when(resolver.refusals()).thenReturn(refusals); + when(resolver.requireWorldGenerator("world_iris_probe", "overworld")).thenThrow(refusal); try (MockedStatic iris = mockStatic(Iris.class); MockedStatic storage = mockStatic(IrisWorldStorage.class)) { @@ -118,7 +118,7 @@ public class BukkitWorldReconcilerRuntimeTest { storage.when(() -> IrisWorldStorage.configuredWorldName(key, "world")).thenReturn("world_iris_probe"); storage.when(() -> IrisWorldStorage.logicalName(key)).thenReturn("probe"); - CompletableFuture created = backend(plugin).createWorld(key, "overworld", 1337L); + CompletableFuture created = backend(resolver).createWorld(key, "overworld", 1337L); ExecutionException failure = assertThrows(ExecutionException.class, created::get); assertSame(refusal, failure.getCause()); @@ -165,14 +165,14 @@ public class BukkitWorldReconcilerRuntimeTest { when(dimension.getLoadKey()).thenReturn("overworld"); when(engine.getData()).thenReturn(data); when(data.getDataFolder()).thenReturn(pack.toFile()); - return new RuntimeFixture(backend(mock(Iris.class)), world, key, generator, engine, history, root, pack); + return new RuntimeFixture(backend(mock(IrisWorldGeneratorResolver.class)), world, key, generator, engine, history, root, pack); } - private static BukkitWorldReconciler.Backend backend(Iris plugin) throws Exception { + private static BukkitWorldReconciler.Backend backend(IrisWorldGeneratorResolver resolver) throws Exception { Class backendClass = Class.forName(BukkitWorldReconciler.class.getName() + "$BukkitBackend"); - Constructor constructor = backendClass.getDeclaredConstructor(Iris.class); + Constructor constructor = backendClass.getDeclaredConstructor(IrisWorldGeneratorResolver.class); constructor.setAccessible(true); - return (BukkitWorldReconciler.Backend) constructor.newInstance(plugin); + return (BukkitWorldReconciler.Backend) constructor.newInstance(resolver); } private record RuntimeFixture(BukkitWorldReconciler.Backend backend, World world, NamespacedKey key, diff --git a/build.gradle b/build.gradle index 09e8800c7..3ba0ac1ba 100644 --- a/build.gradle +++ b/build.gradle @@ -753,7 +753,8 @@ pluginPackaging { policyName = 'Iris Bukkit' packed = true packedJarAccessors = ['art/arcane/iris/platform/bukkit/plugin/VolmitPlugin#getJarFile'] - packedPayloadOnlyPrefixes = ['iris-language-guides/'] + packedPayloadOnlyPrefixes = ['iris-language-guides/', 'META-INF/iris/generation-kernels/abi-', 'iris/icons/views/', 'iris/datapack/'] + packedMaximumBootstrapClasses = 90 stripDirectories = true stripLocalVariables = true releaseCompression = providers.gradleProperty('compactRelease') diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitPlugin.java b/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitPlugin.java index 0939e8649..2c3b7f6e8 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitPlugin.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/plugin/VolmitPlugin.java @@ -19,8 +19,6 @@ package art.arcane.iris.platform.bukkit.plugin; import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.io.IO; import art.arcane.iris.world.task.J; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; @@ -31,11 +29,14 @@ import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; @SuppressWarnings("EmptyMethod") public abstract class VolmitPlugin extends JavaPlugin implements Listener { public static final boolean bad = false; - private final KList postShutdown = new KList<>(); + private final List postShutdown = new ArrayList<>(); public File getJarFile() { return getFile(); @@ -45,7 +46,7 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener { postShutdown.add(r); } - protected void runPostShutdown() { + public void runPostShutdown() { postShutdown.forEach(Runnable::run); } @@ -77,8 +78,6 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener { private void outputInfo() { try { - IO.delete(getDataFolder("info")); - getDataFolder("info").mkdirs(); outputPluginInfo(); } catch (Throwable e) { IrisLogging.reportError(e); @@ -126,15 +125,13 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener { } public File getDataFile(String... strings) { - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); + File f = new File(getDataFolder(), String.join(File.separator, strings)); f.getParentFile().mkdirs(); return f; } public File getDataFileList(String pre, String[] strings) { - KList v = new KList<>(strings); - v.add(0, pre); - File f = new File(getDataFolder(), v.toString(File.separator)); + File f = new File(getDataFolder(), String.join(File.separator, prefixed(pre, strings))); f.getParentFile().mkdirs(); return f; } @@ -144,7 +141,7 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener { return super.getDataFolder(); } - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); + File f = new File(getDataFolder(), String.join(File.separator, strings)); f.mkdirs(); return f; @@ -155,23 +152,25 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener { return super.getDataFolder(); } - File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator)); + File f = new File(getDataFolder(), String.join(File.separator, strings)); return f; } public File getDataFolderList(String pre, String[] strings) { - KList v = new KList<>(strings); - v.add(0, pre); - if (v.size() == 0) { - return super.getDataFolder(); - } - File f = new File(getDataFolder(), v.toString(File.separator)); + File f = new File(getDataFolder(), String.join(File.separator, prefixed(pre, strings))); f.mkdirs(); return f; } + private static List prefixed(String pre, String[] strings) { + List path = new ArrayList<>(strings.length + 1); + path.add(pre); + path.addAll(Arrays.asList(strings)); + return path; + } + public abstract void start(); public abstract void stop(); diff --git a/core/src/test/java/art/arcane/iris/purity/SwallowedFailurePolicyTest.java b/core/src/test/java/art/arcane/iris/purity/SwallowedFailurePolicyTest.java index 90f0ce1d4..69615fc5f 100644 --- a/core/src/test/java/art/arcane/iris/purity/SwallowedFailurePolicyTest.java +++ b/core/src/test/java/art/arcane/iris/purity/SwallowedFailurePolicyTest.java @@ -54,6 +54,7 @@ public class SwallowedFailurePolicyTest { "src/main/java/art/arcane/iris/world/history", "../spi/src/main/java", "../adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java", + "../adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java", "../adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/PendingWorldReplacementManager.java" ); private static final Pattern IGNORED_CATCH = Pattern.compile("^\\s*}?\\s*catch \\([^)]*\\)\\s*\\{\\s*$");