Merge upstream port lane d

NativeStructureWorldgenAccess keeps both sides: writes are still recorded for the stale deferred-record check, and they go through the POI reconciler when one is bound.
This commit is contained in:
piexel committed 2026-11-10 01:32:04 +01:00
commit 4b1d85177f
69 files changed
+2413 -255

No files matched your search

@@ -65,7 +65,6 @@ public final class ModdedDimensionManager {
private static final ConcurrentHashMap<String, Handle> HANDLES = new ConcurrentHashMap<>();
private static final TicketType TELEPORT_WARM_TICKET = new TicketType(TicketType.NO_TIMEOUT,
TicketType.FLAG_LOADING | TicketType.FLAG_KEEP_DIMENSION_ACTIVE);
private static final long TELEPORT_TIMEOUT_SECONDS = 10L;
private static volatile ModdedServerAccess access;
private ModdedDimensionManager() {
@@ -265,18 +264,6 @@ public final class ModdedDimensionManager {
}
}
public static CompletableFuture<Boolean> teleportAsync(
ServerPlayer player,
MinecraftServer server,
String dimensionId,
double x,
double y,
double z
) {
return teleportAsync(player, server, dimensionId, x, y, z,
System.nanoTime() + TimeUnit.SECONDS.toNanos(TELEPORT_TIMEOUT_SECONDS));
}
public static CompletableFuture<Boolean> teleportAsync(
ServerPlayer player,
MinecraftServer server,
@@ -513,7 +500,7 @@ public final class ModdedDimensionManager {
return new TimeoutException("Teleport into " + level.dimension().identifier()
+ " at " + ModdedTeleportBounds.blockCoordinate(x) + ","
+ ModdedTeleportBounds.blockCoordinate(z)
+ " exceeded " + TELEPORT_TIMEOUT_SECONDS + " seconds.");
+ " did not finish before its deadline.");
}
private static void runOnServer(MinecraftServer server, Runnable task) {
@@ -58,6 +58,8 @@ import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.storage.LevelData;
import java.util.ArrayDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public final class ModdedEngineBootstrap {
private static final String[] CORE_SELF_TEST_CLASSES = {
@@ -66,12 +68,17 @@ public final class ModdedEngineBootstrap {
"art.arcane.iris.core.loader.IrisData"
};
private static final Object LOCK = new Object();
private static final Object STOP_LOCK = new Object();
private static final AtomicBoolean EXIT_FLUSH_REGISTERED = new AtomicBoolean();
private static final long EXIT_FLUSH_SERVER_WAIT_SECONDS = 30L;
private static final ModdedServiceManager UNBOUND_SERVICE_MANAGER = new ModdedServiceManager();
private static volatile ModdedLoader loader;
private static volatile BoundRuntime runtime;
private static volatile MinecraftServer currentServer;
private static volatile MinecraftServer spawnCaptureServer;
private static volatile boolean initialSpawnWasDefault;
private static volatile boolean stoppedPending;
private static volatile Thread stoppingThread;
private ModdedEngineBootstrap() {
}
@@ -96,10 +103,12 @@ public final class ModdedEngineBootstrap {
}
public static void start(MinecraftServer server) {
finishPreviousServer("server start");
registerExitFlush();
captureInitialSpawn(server);
currentServer = server;
bind();
// Pair of the stop() burst-pools stage. Load-bearing on integrated servers: once
// Pair of the stopped() burst-pools stage. Load-bearing on integrated servers: once
// closed, MultiBurst falls back to a same-thread executor, so a second world load
// without reopen() would silently run every burst inline.
MultiBurst.burst.reopen();
@@ -125,6 +134,7 @@ public final class ModdedEngineBootstrap {
}
public static void serverAboutToStart(MinecraftServer server) {
finishPreviousServer("server start");
captureInitialSpawn(server);
ModdedStartup.prepareForStartup();
}
@@ -153,20 +163,16 @@ public final class ModdedEngineBootstrap {
try {
generator.unbindEngine(level);
} catch (Throwable exception) {
// Never propagate into the loader's unload loop: an escape there skips closing every later level. A
// runtime dimension removal retries the eviction itself and fails with the retained mapping.
ModdedIrisLog.error("Iris engine unload failed for {}", level.dimension().identifier(), exception);
if (exception instanceof RuntimeException runtimeException) {
throw runtimeException;
}
if (exception instanceof Error fatalError) {
throw fatalError;
}
throw new IllegalStateException("Iris engine unload failed for "
+ level.dimension().identifier(), exception);
}
}
public static void stop() {
MinecraftServer stoppingServer = currentServer;
stoppingThread = Thread.currentThread();
stoppedPending = true;
Throwable failure = null;
failure = runStopStage(failure, "pack downloads", IrisModdedCommands::shutdownDownloads);
failure = runStopStage(failure, "world check", () -> ModdedWorldCheck.serverStopped(stoppingServer));
@@ -179,6 +185,62 @@ public final class ModdedEngineBootstrap {
failure = runStopStage(failure, "studio commands", ModdedStudioCommands::clear);
failure = runStopStage(failure, "gui host", ModdedGuiHost::clear);
failure = runStopStage(failure, "services", () -> services().disableAll());
reportStopFailure("stopping", failure);
}
/**
* The loaders still drain queued chunk generation after server stopping and only close levels afterwards, so
* engines, their mantle and generation history, and the generation pools stay open until the server stopped.
* Engines of unloaded levels are already closed by {@link #levelUnloaded}; this closes whatever remains.
* A loader that throws before firing the stopped event skips it: the next server start or the JVM exit runs
* it instead.
*/
public static void stopped() {
synchronized (STOP_LOCK) {
stoppedPending = false;
stoppingThread = null;
closeStoppedServer();
}
}
private static void finishPreviousServer(String trigger) {
synchronized (STOP_LOCK) {
if (!stoppedPending) {
return;
}
ModdedIrisLog.warn("Iris closing the engines the previous server left open ({})", trigger);
stopped();
}
}
private static void registerExitFlush() {
if (EXIT_FLUSH_REGISTERED.compareAndSet(false, true)) {
Runtime.getRuntime().addShutdownHook(new Thread(ModdedEngineBootstrap::flushAtExit, "Iris Exit Flush"));
}
}
private static void flushAtExit() {
if (!stoppedPending) {
return;
}
Thread serverThread = stoppingThread;
if (serverThread != null && serverThread != Thread.currentThread()) {
try {
serverThread.join(TimeUnit.SECONDS.toMillis(EXIT_FLUSH_SERVER_WAIT_SECONDS));
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return;
}
if (serverThread.isAlive()) {
ModdedIrisLog.warn("Iris skipped its exit flush: the server thread is still stopping");
return;
}
}
finishPreviousServer("JVM exit");
}
private static void closeStoppedServer() {
Throwable failure = null;
failure = runStopStage(failure, "world engines", ModdedWorldEngines::shutdown);
failure = runStopStage(failure, "primary world router", ModdedPrimaryWorldRouter::clear);
failure = runStopStage(failure, "dimension manager", ModdedDimensionManager::clear);
@@ -201,10 +263,14 @@ public final class ModdedEngineBootstrap {
spawnCaptureServer = null;
initialSpawnWasDefault = false;
});
reportStopFailure("stopped", failure);
}
private static void reportStopFailure(String phase, Throwable failure) {
if (failure != null) {
// The shutdown path must not propagate: propagating aborts the remaining loader stop handlers and
// can leave the level unsaved. Every stage already logged its own failure.
ModdedIrisLog.error("Iris modded shutdown completed with failures", failure);
ModdedIrisLog.error("Iris modded shutdown ({}) completed with failures", phase, failure);
}
}
@@ -101,7 +101,8 @@ public final class ModdedPrimaryWorldRouter {
primary,
player.getX(),
Double.MIN_VALUE,
player.getZ());
player.getZ(),
ModdedTeleportDeadline.fromNow());
teleport.whenComplete((success, failure) -> {
inFlight.remove(id);
if (Boolean.TRUE.equals(success) && failure == null) {
@@ -192,7 +192,8 @@ public final class ModdedScheduler implements PlatformScheduler {
mainQueue.clear();
delayedQueue.clear();
mainThread = null;
// Shutdown stage that always runs (ModdedEngineBootstrap.stop): release the level snapshot with it.
// Runs from ModdedEngineBootstrap.stopped, or its fallback at the next server start or JVM exit when the
// loader skipped it: release the level snapshot with it.
ModdedServerLevels.forget();
}
@@ -0,0 +1,36 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.modded;
import java.util.concurrent.TimeUnit;
/**
* Deadline for a teleport that waits on its destination chunk. The first chunk of a cold dimension also loads the
* pack and binds the engine; the deadline only bounds a destination whose chunk never completes.
*/
public final class ModdedTeleportDeadline {
private static final long DEADLINE_SECONDS = 120L;
private ModdedTeleportDeadline() {
}
public static long fromNow() {
return System.nanoTime() + TimeUnit.SECONDS.toNanos(DEADLINE_SECONDS);
}
}
@@ -225,9 +225,9 @@ public final class ModdedWorldEngines {
Engine engine = entry.getValue();
try {
// Latch the generator's unloading flag BEFORE closing (unbindEngine sets it,
// then evicts): chunk-system drain work running after this stage would
// otherwise see a closed engine and silently rebuild a fresh engine + Mantle
// that no teardown stage ever closes, writing plates after the final save.
// then evicts): late chunk work would otherwise see a closed engine and
// silently rebuild a fresh engine + Mantle that no teardown stage ever
// closes, writing plates after the final save.
if (level.getChunkSource().getGenerator() instanceof IrisModdedChunkGenerator generator) {
generator.unbindEngine(level);
} else {
@@ -36,6 +36,7 @@ import art.arcane.iris.modded.ModdedForcedDatapack;
import art.arcane.iris.modded.ModdedLoader;
import art.arcane.iris.modded.ModdedScheduler;
import art.arcane.iris.modded.ModdedServerLevels;
import art.arcane.iris.modded.ModdedTeleportDeadline;
import art.arcane.iris.modded.ModdedWorldgenIds;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.collection.KMap;
@@ -58,6 +59,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import art.arcane.volmlib.util.localization.MessageArgument;
@@ -135,7 +137,8 @@ public final class IrisModdedCommands {
dimensionId,
8.5D,
Double.MIN_VALUE,
8.5D);
8.5D,
ModdedTeleportDeadline.fromNow());
teleport.whenComplete((success, failure) -> {
if (Boolean.TRUE.equals(success) && failure == null) {
return;
@@ -144,14 +147,43 @@ public final class IrisModdedCommands {
ModdedIrisLog.error("Iris teleport into '{}' failed for {}",
dimensionId, player.getUUID(), failure);
}
server.execute(() -> fail(source, IrisLanguage.plain(
ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_DIMENSION_IS_NOT_LOADED,
MessageArgument.untrusted("dimensionId", dimensionId))));
server.execute(() -> fail(source, teleportFailure(dimensionId, player.getScoreboardName(), failure,
ModdedDimensionManager.level(server, dimensionId) != null,
server.getPlayerList().getPlayer(player.getUUID()) != null)));
});
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORTING, MessageArgument.untrusted("value", player.getScoreboardName()), MessageArgument.untrusted("dimensionId", dimensionId)));
return 1;
}
static String teleportFailure(String dimensionId, String playerName, Throwable failure,
boolean dimensionLoaded, boolean playerOnline) {
if (failure != null) {
return IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_REASON,
MessageArgument.untrusted("dimensionId", dimensionId),
MessageArgument.untrusted("reason", failureReason(failure)));
}
if (!dimensionLoaded) {
return IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_DIMENSION_IS_NOT_LOADED,
MessageArgument.untrusted("dimensionId", dimensionId));
}
if (!playerOnline) {
return IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_CANCELLED_PLAYER_OFFLINE,
MessageArgument.untrusted("dimensionId", dimensionId),
MessageArgument.untrusted("value", playerName));
}
return IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_REFUSED,
MessageArgument.untrusted("dimensionId", dimensionId));
}
private static String failureReason(Throwable failure) {
Throwable cause = failure;
while (cause instanceof CompletionException && cause.getCause() != null) {
cause = cause.getCause();
}
String message = cause.getMessage();
return message == null || message.isBlank() ? cause.getClass().getSimpleName() : message;
}
static int evacuate(CommandSourceStack source, ServerLevel target) {
MinecraftServer server = source.getServer();
ServerLevel level = target != null ? target : source.getLevel();
@@ -262,20 +294,7 @@ public final class IrisModdedCommands {
&& !irisGenerator.dimensionKey().contains(filter)) {
continue;
}
Engine engine = irisGenerator.engineIfBound();
if (engine == null) {
lines.add(irisIdentity + ": pack=" + irisGenerator.dimensionKey()
+ " world=" + dimensionId + " (engine not started yet)");
continue;
}
String featureStatus = irisGenerator.importedFeaturesStatus();
lines.add(irisIdentity + ": pack=" + engine.getDimension().getLoadKey()
+ " world=" + dimensionId
+ (showSeed ? " seed=" + level.getSeed() : "")
+ " height=" + engine.getMinHeight() + ".." + engine.getMaxHeight()
+ " generated=" + engine.getGenerated()
+ (featureStatus == null ? "" : " importedFeatures=" + featureStatus)
+ " data=" + engine.getData().getDataFolder().getName());
lines.add(worldRow(dimensionId, irisGenerator.dimensionKey(), irisGenerator.engineIfBound(), showSeed, irisGenerator.importedFeaturesStatus()));
}
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_LOADED_DIMENSIONS_IRIS, MessageArgument.untrusted("total", total), MessageArgument.untrusted("iris", iris)));
if (lines.isEmpty()) {
@@ -292,6 +311,26 @@ public final class IrisModdedCommands {
return 1;
}
record WorldRow(String dimensionId, String packKey, long seed, int minHeight, int maxHeight, int generated, String dataName) {
String format(boolean showSeed, String featureStatus) {
return dimensionId + ": pack=" + packKey
+ (showSeed ? " seed=" + seed : "")
+ " height=" + minHeight + ".." + maxHeight
+ " generated=" + generated
+ (featureStatus == null ? "" : " importedFeatures=" + featureStatus)
+ " data=" + dataName;
}
}
static String worldRow(String dimensionId, String dimensionKey, Engine engine, boolean showSeed, String featureStatus) {
if (engine == null) {
return dimensionId + ": pack=" + dimensionKey + " (engine not started yet)";
}
return new WorldRow(dimensionId, engine.getDimension().getLoadKey(), engine.getWorld().getRawWorldSeed(),
engine.getMinHeight(), engine.getMaxHeight(), engine.getEngineData().getStatistics().getChunksGenerated(),
engine.getData().getDataFolder().getName()).format(showSeed, featureStatus);
}
static int seed(CommandSourceStack source) {
ServerLevel level = source.getLevel();
Engine engine = engineFor(level);
@@ -299,7 +338,7 @@ public final class IrisModdedCommands {
fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_14));
return 0;
}
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_WORLD_SEED, MessageArgument.untrusted("value", level.getSeed())));
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_WORLD_SEED, MessageArgument.untrusted("value", engine.getWorld().getRawWorldSeed())));
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_ENGINE_SEED_MIXED, MessageArgument.untrusted("value", engine.getSeedManager().getSeed()), MessageArgument.untrusted("value2", engine.getSeedManager().getFullMixedSeed())));
return 1;
}
@@ -25,6 +25,7 @@ import art.arcane.iris.engine.framework.Engine;
import art.arcane.iris.engine.framework.render.RenderType;
import art.arcane.iris.modded.ModdedDimensionManager;
import art.arcane.iris.modded.ModdedIrisLog;
import art.arcane.iris.modded.ModdedTeleportDeadline;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
@@ -37,7 +38,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public final class ModdedVisionOverlay implements GuiOverlay {
@@ -103,7 +103,7 @@ public final class ModdedVisionOverlay implements GuiOverlay {
blockX + 0.5D,
surfaceY,
blockZ + 0.5D,
System.nanoTime() + TimeUnit.SECONDS.toNanos(10L));
ModdedTeleportDeadline.fromNow());
UUID playerId = player.getUUID();
teleport.whenComplete((success, failure) -> {
if (failure != null) {
@@ -33,6 +33,7 @@ import art.arcane.iris.modded.api.ModdedBlockData;
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.function.Consumer3;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
@@ -40,6 +41,7 @@ import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import art.arcane.volmlib.util.matter.MatterUpdate;
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import net.minecraft.core.BlockPos;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
@@ -60,6 +62,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
public final class ModdedChunkUpdateService implements ModdedTickableService {
private static final long PASS_PERIOD_MILLIS = 3_000L;
@@ -154,7 +157,7 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
int centerZ = player.blockPosition().getZ() >> 4;
for (int dx = -PLAYER_CHUNK_RADIUS; dx <= PLAYER_CHUNK_RADIUS; dx++) {
for (int dz = -PLAYER_CHUNK_RADIUS; dz <= PLAYER_CHUNK_RADIUS; dz++) {
updateChunk(engine, level, centerX + dx, centerZ + dz);
updatePassChunk(engine, level, centerX + dx, centerZ + dz);
}
}
}
@@ -162,7 +165,7 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
private void updateForcedChunks(Engine engine, ServerLevel level) {
for (long chunkKey : level.getForceLoadedChunks()) {
updateChunk(engine, level, ChunkPos.getX(chunkKey), ChunkPos.getZ(chunkKey));
updatePassChunk(engine, level, ChunkPos.getX(chunkKey), ChunkPos.getZ(chunkKey));
}
}
@@ -170,8 +173,30 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
updateChunk(engine, level, chunkX, chunkZ, false);
}
private void updateChunk(Engine engine, ServerLevel level, int chunkX, int chunkZ) {
updateChunk(engine, level, chunkX, chunkZ, true);
private void updatePassChunk(Engine engine, ServerLevel level, int chunkX, int chunkZ) {
isolateChunkFailure(
() -> updateChunk(engine, level, chunkX, chunkZ, true),
() -> engine.isClosed() || engine.getMantle().getMantle().isClosed(),
String.valueOf(level.dimension().identifier()),
chunkX,
chunkZ);
}
static void isolateChunkFailure(Runnable chunkUpdate, BooleanSupplier passEnded, String levelName, int chunkX, int chunkZ) {
try {
chunkUpdate.run();
} catch (RuntimeException failure) {
if (passEnded.getAsBoolean()) {
throw failure;
}
boolean firstFailure = IrisLogging.errorOnce(
"chunk-update:" + levelName + ":" + chunkX + "," + chunkZ + ":" + failure,
"Iris chunk update failed at %s,%s in %s, retrying each pass: %s",
chunkX, chunkZ, levelName, failure);
if (firstFailure) {
IrisLogging.reportError(failure);
}
}
}
private void updateChunk(Engine engine, ServerLevel level, int chunkX, int chunkZ, boolean requireNeighbors) {
@@ -354,15 +379,49 @@ public final class ModdedChunkUpdateService implements ModdedTickableService {
}
}
chunk.iterate(MatterUpdate.class, (Integer x, Integer yf, Integer z, MatterUpdate v) -> {
if (v != null && v.isUpdate()) {
update(engine, level, x, yf + minHeight, z, baseX, baseZ, chunk);
}
});
chunk.deleteSlices(MatterUpdate.class);
applyQueuedUpdates(chunk, (Integer x, Integer yf, Integer z) ->
update(engine, level, x, yf + minHeight, z, baseX, baseZ, chunk));
engine.getMetrics().getUpdates().put(stopwatch.getMilliseconds());
}
static void applyQueuedUpdates(MantleChunk<Matter> chunk, Consumer3<Integer, Integer, Integer> update) {
IntArrayList completed = new IntArrayList();
try {
chunk.iterate(MatterUpdate.class, (Integer x, Integer yf, Integer z, MatterUpdate v) -> {
if (v != null && v.isUpdate()) {
update.accept(x, yf, z);
completed.add(packUpdatePosition(x, yf, z));
}
});
} catch (RuntimeException | Error failure) {
forgetCompletedUpdates(chunk, completed, failure);
throw failure;
}
chunk.deleteSlices(MatterUpdate.class);
}
private static int packUpdatePosition(int x, int yf, int z) {
return (yf << 8) | ((x & 15) << 4) | (z & 15);
}
private static void forgetCompletedUpdates(MantleChunk<Matter> chunk, IntArrayList completed, Throwable failure) {
try {
for (int index = 0; index < completed.size(); index++) {
int position = completed.getInt(index);
int yf = position >>> 8;
Matter section = chunk.get(yf >> 4);
if (section != null && section.hasSlice(MatterUpdate.class)) {
section.<MatterUpdate>getSlice(MatterUpdate.class)
.set((position >> 4) & 15, yf & 15, position & 15, null);
}
}
} catch (RuntimeException | Error cleanupFailure) {
if (cleanupFailure != failure) {
failure.addSuppressed(cleanupFailure);
}
}
}
private void update(Engine engine, ServerLevel level, int x, int y, int z, int baseX, int baseZ, MantleChunk<Matter> chunk) {
if (y < level.getMinY() || y >= level.getMaxY()) {
return;
@@ -0,0 +1,88 @@
package art.arcane.iris.modded;
import art.arcane.iris.core.IrisSettings;
import art.arcane.iris.modded.command.IrisModdedCommands;
import art.arcane.iris.util.common.parallel.MultiBurst;
import net.minecraft.SharedConstants;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.MinecraftServer;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
public class ModdedEngineBootstrapShutdownTest {
private static final long WORKER_TIMEOUT_SECONDS = 10L;
private static final Callable<Thread> RUNNING_THREAD = Thread::currentThread;
private IrisSettings previousSettings;
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
@Before
public void openRuntime() {
previousSettings = IrisSettings.settings;
IrisSettings.settings = new IrisSettings();
reopenBurstPools();
}
@After
public void restoreRuntime() {
reopenBurstPools();
IrisModdedCommands.openDownloadAdmission();
IrisSettings.settings = previousSettings;
}
@Test
public void serverStoppingKeepsTheGenerationPoolsOpenUntilServerStopped() throws Exception {
ModdedEngineBootstrap.stop();
assertNotSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
ModdedEngineBootstrap.stopped();
assertSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
}
@Test
public void nextServerStartClosesWhatAServerThatNeverReachedStoppedLeftOpen() throws Exception {
ModdedEngineBootstrap.stop();
try (MockedStatic<ModdedStartup> startup = mockStatic(ModdedStartup.class)) {
ModdedEngineBootstrap.serverAboutToStart(mock(MinecraftServer.class));
}
assertSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
}
@Test
public void serverStartLeavesTheGenerationPoolsAloneWhenTheServerStoppedNormally() throws Exception {
ModdedEngineBootstrap.stop();
ModdedEngineBootstrap.stopped();
MultiBurst.burst.reopen();
try (MockedStatic<ModdedStartup> startup = mockStatic(ModdedStartup.class)) {
ModdedEngineBootstrap.serverAboutToStart(mock(MinecraftServer.class));
}
assertNotSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
}
private static void reopenBurstPools() {
MultiBurst.burst.reopen();
MultiBurst.ioBurst.reopen();
}
}
@@ -120,10 +120,10 @@ public class ModdedGenerationLeaseContractTest {
String bootstrap = source("art/arcane/iris/modded/ModdedEngineBootstrap.java");
String stop = method(bootstrap, "public static void stop()");
int downloads = stop.indexOf("IrisModdedCommands::shutdownDownloads");
int scheduler = stop.indexOf("scheduler::shutdown");
assertTrue(downloads >= 0);
assertTrue(scheduler > downloads);
assertTrue(stop.contains("IrisModdedCommands::shutdownDownloads"));
assertFalse(stop.contains("scheduler::shutdown"));
String stopped = method(bootstrap, "private static void closeStoppedServer()");
assertTrue(stopped.contains("scheduler::shutdown"));
}
@Test
@@ -141,21 +141,27 @@ public class ModdedLifecycleFailureContractTest {
@Test
public void engineBootstrapResetsStartupExactlyOnceDuringStop() throws IOException {
String source = source("ModdedEngineBootstrap.java");
String stop = method(source, "public static void stop(");
String stopped = method(source, "private static void closeStoppedServer(");
assertEquals(1, occurrences(stop, "ModdedStartup::reset"));
assertEquals(1, occurrences(source, "ModdedStartup::reset"));
assertEquals(1, occurrences(stopped, "ModdedStartup::reset"));
}
@Test
public void engineBootstrapAttemptsEveryShutdownStageAndAggregatesFailures() throws IOException {
String source = source("ModdedEngineBootstrap.java");
String stop = method(source, "public static void stop(");
String stopped = method(source, "private static void closeStoppedServer(");
assertBefore(stop, "\"services\"", "\"world engines\"");
assertBefore(stop, "\"world engines\"", "\"dimension manager\"");
assertBefore(stop, "\"server state\"", "if (failure != null)");
assertTrue(stop.contains("\"services\""));
assertFalse(stop.contains("\"world engines\""));
assertBefore(stopped, "\"world engines\"", "\"dimension manager\"");
assertBefore(stopped, "\"server state\"", "reportStopFailure(\"stopped\", failure);");
assertBefore(stop, "\"services\"", "reportStopFailure(\"stopping\", failure);");
assertFalse(stop.contains("throw"));
assertTrue(stop.contains("ModdedIrisLog.error(\"Iris modded shutdown completed with failures\", failure);"));
assertFalse(stopped.contains("throw"));
String report = method(source, "private static void reportStopFailure(");
assertTrue(report.contains("ModdedIrisLog.error(\"Iris modded shutdown ({}) completed with failures\", phase, failure);"));
String runStage = method(source, "private static Throwable runStopStage(");
assertTrue(runStage.contains("catch (Throwable stageFailure)"));
@@ -206,12 +212,12 @@ public class ModdedLifecycleFailureContractTest {
}
@Test
public void loaderUnloadSurfacesCloseFailureAndDynamicRemovalUsesStrictEviction() throws IOException {
public void loaderUnloadLogsCloseFailureAndDynamicRemovalUsesStrictEviction() throws IOException {
String bootstrapSource = source("ModdedEngineBootstrap.java");
String unload = method(bootstrapSource, "public static void levelUnloaded(ServerLevel level)");
String failure = catchBlock(unload);
assertTrue(failure.contains("ModdedIrisLog.error("));
assertTrue(failure.contains("throw "));
assertFalse(failure.contains("throw "));
String managerSource = source("ModdedDimensionManager.java");
String remove = method(managerSource, "public static boolean remove(MinecraftServer server, String dimensionId, boolean wipeStorage)");
@@ -0,0 +1,19 @@
package art.arcane.iris.modded;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue;
public class ModdedTeleportDeadlineTest {
@Test
public void deadlineOutlastsAColdFirstChunkAndStaysBounded() {
long before = System.nanoTime();
long deadline = ModdedTeleportDeadline.fromNow();
long after = System.nanoTime();
assertTrue("deadline must outlast a cold first chunk", deadline - before >= TimeUnit.SECONDS.toNanos(60L));
assertTrue("deadline must be bounded", deadline - after <= TimeUnit.SECONDS.toNanos(120L));
}
}
@@ -0,0 +1,48 @@
package art.arcane.iris.modded.command;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.localization.ModdedCommandMessages;
import art.arcane.volmlib.util.localization.MessageArgument;
import org.junit.Test;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
public class IrisModdedCommandsTeleportTest {
private static final String DIMENSION = "irisworldgen:1";
@Test
public void failureReportsItsRootCauseInsteadOfAnUnloadedDimension() {
String message = IrisModdedCommands.teleportFailure(DIMENSION, "Tester",
new CompletionException(new IllegalStateException("Exception generating new chunk")), true, true);
assertEquals(IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_REASON,
MessageArgument.untrusted("dimensionId", DIMENSION),
MessageArgument.untrusted("reason", "Exception generating new chunk")), message);
}
@Test
public void failureWithoutMessageNamesTheFailureType() {
String message = IrisModdedCommands.teleportFailure(DIMENSION, "Tester", new TimeoutException(), true, true);
assertEquals(IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_REASON,
MessageArgument.untrusted("dimensionId", DIMENSION),
MessageArgument.untrusted("reason", "TimeoutException")), message);
}
@Test
public void unloadedDimensionIsReportedOnlyWhenItIsGone() {
assertEquals(IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_DIMENSION_IS_NOT_LOADED,
MessageArgument.untrusted("dimensionId", DIMENSION)),
IrisModdedCommands.teleportFailure(DIMENSION, "Tester", null, false, true));
assertEquals(IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_CANCELLED_PLAYER_OFFLINE,
MessageArgument.untrusted("dimensionId", DIMENSION),
MessageArgument.untrusted("value", "Tester")),
IrisModdedCommands.teleportFailure(DIMENSION, "Tester", null, true, false));
assertEquals(IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_REFUSED,
MessageArgument.untrusted("dimensionId", DIMENSION)),
IrisModdedCommands.teleportFailure(DIMENSION, "Tester", null, true, true));
}
}
@@ -0,0 +1,54 @@
package art.arcane.iris.modded.command;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class IrisModdedWorldListingTest {
private static final String ALPHA = "iris:alpha";
private static final String BETA = "iris:beta";
private static final long ALPHA_SEED = 424242L;
private static final long BETA_SEED = -77L;
private static final int ALPHA_CHUNKS = 1089;
@Test
public void rowShowsTheIrisWorldSeedAndPersistedChunkCount() {
String alpha = row(ALPHA, ALPHA_SEED, ALPHA_CHUNKS).format(true, null);
String beta = row(BETA, BETA_SEED, 0).format(true, null);
assertTrue(alpha, alpha.startsWith(ALPHA + ": pack=overworld "));
assertTrue(alpha, alpha.contains(" seed=424242 "));
assertTrue(alpha, alpha.contains(" generated=1089 "));
assertTrue(beta, beta.startsWith(BETA + ": pack=overworld "));
assertTrue(beta, beta.contains(" seed=-77 "));
assertTrue(beta, beta.contains(" generated=0 "));
assertFalse(alpha, alpha.contains(" world="));
}
@Test
public void rowOmitsTheSeedWhenItIsNotShown() {
String row = row(ALPHA, ALPHA_SEED, ALPHA_CHUNKS).format(false, null);
assertFalse(row, row.contains("seed="));
assertTrue(row, row.contains(" generated=1089 "));
}
@Test
public void rowAppendsImportedFeatureStatus() {
String row = row(ALPHA, ALPHA_SEED, ALPHA_CHUNKS).format(true, "ready");
assertTrue(row, row.contains(" importedFeatures=ready "));
}
@Test
public void rowForAnUnstartedEngineIsLabeledByItsDimension() {
assertEquals("iris:gamma: pack=overworld:overworld (engine not started yet)",
IrisModdedCommands.worldRow("iris:gamma", "overworld:overworld", null, true, null));
}
private static IrisModdedCommands.WorldRow row(String dimensionId, long seed, int generated) {
return new IrisModdedCommands.WorldRow(dimensionId, "overworld", seed, -64, 320, generated, "overworld");
}
}
@@ -1,20 +1,34 @@
package art.arcane.iris.modded.service;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.util.project.matter.TileWrapper;
import art.arcane.volmlib.util.function.Consumer4;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.mantle.runtime.MantleDataAdapter;
import art.arcane.volmlib.util.mantle.runtime.MantleHooks;
import art.arcane.volmlib.util.matter.IrisMatter;
import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterSlice;
import art.arcane.volmlib.util.matter.MatterUpdate;
import art.arcane.volmlib.util.matter.slices.UpdateMatter;
import org.junit.Test;
import org.mockito.MockedStatic;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mockStatic;
public class ModdedChunkUpdateServiceTest {
@Test
@@ -63,6 +77,93 @@ public class ModdedChunkUpdateServiceTest {
assertEquals(List.of("materialize"), chunk.operations());
}
@Test
public void failedUpdateForgetsOnlyTheUpdatesAlreadyApplied() {
ChestUpdateMantleChunk chunk = new ChestUpdateMantleChunk();
assertThrows(IllegalStateException.class, () ->
ModdedChunkUpdateService.applyQueuedUpdates(chunk, (Integer x, Integer yf, Integer z) -> {
if (x == 2) {
throw new IllegalStateException("update failure");
}
}));
assertFalse(chunk.deleted());
assertNull(chunk.slice.get(1, 5, 1));
assertNotNull(chunk.slice.get(2, 5, 2));
}
@Test
public void failedChunkIsReportedAndTheNextChunkStillRuns() {
AtomicInteger updatedChunks = new AtomicInteger();
try (MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
logging.when(() -> IrisLogging.errorOnce(anyString(), anyString(), any(Object[].class))).thenReturn(true);
ModdedChunkUpdateService.isolateChunkFailure(
() -> {
throw new IllegalStateException("chunk failure");
},
() -> false, "example:updates", 0, 0);
ModdedChunkUpdateService.isolateChunkFailure(
updatedChunks::incrementAndGet, () -> false, "example:updates", 4, 0);
assertEquals(1, updatedChunks.get());
logging.verify(() -> IrisLogging.errorOnce(anyString(), anyString(), any(Object[].class)));
logging.verify(() -> IrisLogging.reportError(any(Throwable.class)));
}
}
@Test
public void endedPassRethrowsTheChunkFailure() {
IllegalStateException failure = new IllegalStateException("chunk failure");
IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
ModdedChunkUpdateService.isolateChunkFailure(
() -> {
throw failure;
},
() -> true, "example:updates", 0, 0));
assertSame(failure, thrown);
}
private static final class ChestUpdateMantleChunk extends MantleChunk<Matter> {
private final Matter section = new IrisMatter(16, 16, 16);
private final MatterSlice<MatterUpdate> slice = section.slice(MatterUpdate.class);
private boolean deleted;
private ChestUpdateMantleChunk() {
super(1, 0, 0, emptyAdapter(), MantleHooks.NONE);
slice.set(1, 5, 1, UpdateMatter.ON);
slice.set(2, 5, 2, UpdateMatter.ON);
}
@Override
public Matter get(int index) {
return section;
}
@Override
public <T> void iterate(Class<T> type, Consumer4<Integer, Integer, Integer, T> iterator) {
if (type == MatterUpdate.class) {
iterator.accept(1, 5, 1, type.cast(UpdateMatter.ON));
iterator.accept(2, 5, 2, type.cast(UpdateMatter.ON));
}
}
@Override
public void deleteSlices(Class<?> type) {
if (type == MatterUpdate.class) {
deleted = true;
}
}
private boolean deleted() {
return deleted;
}
}
private static final class RecordingMantleChunk extends MantleChunk<Matter> {
private final ArrayList<String> operations = new ArrayList<>();