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

@@ -1153,6 +1153,11 @@ public class NMSBinding implements INMSBinding {
}
}
@Override
public void reconcileNativeStructurePois(Chunk chunk) {
NativeStructurePoiUpdates.reconcile((LevelChunk) ((CraftChunk) chunk).getHandle(ChunkStatus.FULL));
}
@Override
public boolean clearChunkBlocks(Chunk bukkitChunk) {
try {
@@ -0,0 +1,142 @@
package art.arcane.iris.core.nms.v26_2_R1;
import ca.spottedleaf.moonrise.common.util.TickThread;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.SectionPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.ai.village.poi.PoiManager;
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
import net.minecraft.world.entity.ai.village.poi.PoiSection;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.ProtoChunk;
import org.bukkit.NamespacedKey;
import org.bukkit.persistence.PersistentDataType;
import java.util.Arrays;
import java.util.Optional;
final class NativeStructurePoiUpdates {
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
private final int skipPoiFlag;
NativeStructurePoiUpdates(int skipPoiFlag) {
this.skipPoiFlag = skipPoiFlag;
}
static NativeStructurePoiUpdates create() {
try {
return new NativeStructurePoiUpdates(Block.class.getField("UPDATE_SKIP_POI").getInt(null));
} catch (NoSuchFieldException e) {
return null;
} catch (IllegalAccessException e) {
throw new ExceptionInInitializerError(e);
}
}
boolean setBlock(WorldGenLevel world, BlockPos position, BlockState state, int flags, int limit) {
if ((flags & skipPoiFlag) != 0) {
return world.setBlock(position, state, flags, limit);
}
ChunkAccess chunk = world.getChunk(position);
if (!(chunk instanceof ProtoChunk)) {
return world.setBlock(position, state, flags, limit);
}
if (!(chunk instanceof ImposterProtoChunk)
&& !PoiTypes.forState(chunk.getBlockState(position)).equals(PoiTypes.forState(state))) {
markSection(chunk, chunk.getSectionIndex(position.getY()));
}
return world.setBlock(position, state, flags | skipPoiFlag, limit);
}
static void reconcile(LevelChunk chunk) {
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
if (sections == null) {
return;
}
validateSections(chunk, sections);
ServerLevel world = (ServerLevel) chunk.getLevel();
TickThread.ensureTickThread(world, chunk.getPos(), "Native structure POIs require the chunk owning thread");
PoiManager manager = world.getPoiManager();
for (int word = 0; word < sections.length; word++) {
long remaining = sections[word];
while (remaining != 0) {
int index = (word << 6) + Long.numberOfTrailingZeros(remaining);
reconcileSection(chunk, manager, index);
remaining &= remaining - 1;
}
}
chunk.persistentDataContainer.remove(DIRTY_SECTIONS);
chunk.markUnsaved();
}
private static void markSection(ChunkAccess chunk, int index) {
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
int word = index >>> 6;
long bit = 1L << (index & 63);
if (sections == null) {
sections = new long[word + 1];
} else {
validateSections(chunk, sections);
if (word < sections.length && (sections[word] & bit) != 0) {
return;
}
if (word >= sections.length) {
sections = Arrays.copyOf(sections, word + 1);
}
}
sections[word] |= bit;
chunk.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, sections);
}
private static void validateSections(ChunkAccess chunk, long[] sections) {
int count = chunk.getSectionsCount();
int words = (count + 63) >>> 6;
if (sections.length > words
|| sections.length == words && (count & 63) != 0
&& (sections[words - 1] >>> (count & 63)) != 0) {
throw new IllegalArgumentException("Native POI repair sections exceed chunk height at " + chunk.getPos());
}
}
private static void reconcileSection(LevelChunk chunk, PoiManager manager, int index) {
SectionPos sectionPosition = SectionPos.of(chunk.getPos(), chunk.getSectionYFromSectionIndex(index));
Optional<PoiSection> existing = manager.getOrLoad(sectionPosition.asLong());
if (existing.isPresent()) {
for (PoiRecord record : existing.get().getRecords(type -> true, PoiManager.Occupancy.ANY).toList()) {
if (!PoiTypes.forState(chunk.getBlockState(record.getPos())).equals(Optional.of(record.getPoiType()))) {
manager.remove(record.getPos());
}
}
}
LevelChunkSection section = chunk.getSection(index);
if (!section.maybeHas(PoiTypes::hasPoi)) {
return;
}
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
for (int y = 0; y < 16; y++) {
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
Optional<Holder<PoiType>> type = PoiTypes.forState(section.getBlockState(x, y, z));
if (type.isEmpty()) {
continue;
}
position.set(sectionPosition.minBlockX() + x, sectionPosition.minBlockY() + y,
sectionPosition.minBlockZ() + z);
if (!manager.getType(position).equals(type)) {
manager.add(position.immutable(), type.get());
}
}
}
}
}
}
@@ -12,6 +12,7 @@ import net.minecraft.core.RegistryAccess;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.WorldGenRegion;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
@@ -60,6 +61,7 @@ import java.util.function.Supplier;
final class NativeStructureWorldgenAccess implements WorldGenLevel {
private static final int WRITE_RADIUS = 1;
private static final NativeStructurePoiUpdates POI_UPDATES = NativeStructurePoiUpdates.create();
private final WorldGenLevel delegate;
private final ChunkPos generationCenter;
@@ -426,23 +428,45 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
@Override
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
return recordWrite(position, isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit));
if (!isWritable(position)) {
return false;
}
return recordWrite(position, POI_UPDATES != null
? POI_UPDATES.setBlock(delegate, position, state, updateFlags, updateLimit)
: delegate.setBlock(position, state, updateFlags, updateLimit));
}
@Override
public boolean removeBlock(BlockPos position, boolean move) {
return recordWrite(position, isWritable(position) && delegate.removeBlock(position, move));
if (!isWritable(position)) {
return false;
}
if (reconcilesPoiThroughSetBlock()) {
return setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, Block.UPDATE_LIMIT);
}
return recordWrite(position, delegate.removeBlock(position, move));
}
@Override
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
return recordWrite(position, isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit));
if (!isWritable(position)) {
return false;
}
if (reconcilesPoiThroughSetBlock()) {
return !delegate.getBlockState(position).isAir()
&& setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, updateLimit);
}
return recordWrite(position, delegate.destroyBlock(position, drop, source, updateLimit));
}
WrittenBlocks writtenBlocks() {
return writtenBlocks;
}
private boolean reconcilesPoiThroughSetBlock() {
return POI_UPDATES != null && delegate instanceof WorldGenRegion;
}
private boolean recordWrite(BlockPos position, boolean written) {
if (written) {
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
@@ -0,0 +1,250 @@
package art.arcane.iris.core.nms.v26_2_R1;
import ca.spottedleaf.moonrise.common.util.TickThread;
import com.mojang.serialization.Codec;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.IdMapper;
import net.minecraft.core.SectionPos;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.ai.village.poi.PoiManager;
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
import net.minecraft.world.entity.ai.village.poi.PoiSection;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.PalettedContainerFactory;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.Strategy;
import net.minecraft.world.level.chunk.UpgradeData;
import org.bukkit.NamespacedKey;
import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry;
import org.bukkit.craftbukkit.persistence.DirtyCraftPersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
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.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class NativeStructurePoiUpdatesTest {
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
@BeforeClass
public static void bootstrapMinecraftRegistries() {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
@Test
public void generationRecordsIntentBeforeSuppressingNativePoiCallbacks() {
Fixture fixture = new Fixture();
BlockPos position = new BlockPos(-31, 5, 49);
doAnswer(call -> {
assertNotNull(fixture.proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY));
assertEquals(Block.UPDATE_CLIENTS | 4096, (int) call.getArgument(2));
fixture.proto.setBlockState(position, call.getArgument(1), 0);
return true;
}).when(fixture.world).setBlock(any(), any(), anyInt(), anyInt());
assertTrue(fixture.updates.setBlock(fixture.world, position,
Blocks.COMPOSTER.defaultBlockState(), Block.UPDATE_CLIENTS, 17));
assertArrayEquals(new long[]{16L}, fixture.marker());
}
@Test
public void denseWritesStoreOneSectionBitAndSurvivePersistentDataRoundTrip() throws Exception {
Fixture fixture = new Fixture();
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
fixture.write(new BlockPos(-32 + x, 5, 48 + z), Blocks.COMPOSTER.defaultBlockState());
}
}
assertArrayEquals(new long[]{16L}, fixture.marker());
DirtyCraftPersistentDataContainer restored = new DirtyCraftPersistentDataContainer(new CraftPersistentDataTypeRegistry());
restored.putAll(fixture.proto.persistentDataContainer.toTagCompound());
fixture.loaded.persistentDataContainer = restored;
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
assertEquals(256L, fixture.records().getRecords(type -> true, PoiManager.Occupancy.ANY).count());
assertFalse(restored.has(DIRTY_SECTIONS));
}
@Test
public void validSectionsReconcileFinalStatesAndKeepMatchingClaimedTickets() throws Exception {
Fixture fixture = new Fixture();
BlockPos retained = new BlockPos(-31, 5, 49);
BlockPos replaced = new BlockPos(-30, 5, 49);
BlockPos removed = new BlockPos(-29, 5, 49);
Holder<PoiType> farmer = PoiTypes.forState(Blocks.COMPOSTER.defaultBlockState()).orElseThrow();
PoiSection existing = new PoiSection.Packed(true, List.of(
new PoiRecord.Packed(retained, farmer, 0),
new PoiRecord.Packed(replaced, farmer, 1),
new PoiRecord.Packed(removed, farmer, 1))).unpack(() -> {});
fixture.pois.put(SectionPos.of(retained).asLong(), existing);
PoiRecord retainedRecord = existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow();
for (BlockPos position : List.of(retained, replaced, removed)) {
fixture.proto.setBlockState(position, Blocks.COMPOSTER.defaultBlockState(), 0);
}
fixture.write(replaced, Blocks.BARREL.defaultBlockState());
fixture.write(removed, Blocks.AIR.defaultBlockState());
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
assertEquals(PoiTypes.forState(Blocks.BARREL.defaultBlockState()), existing.getType(replaced));
assertTrue(existing.getType(removed).isEmpty());
assertSame(retainedRecord, existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow());
assertEquals(0, existing.getFreeTickets(retained));
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
assertEquals(0, existing.getFreeTickets(retained));
}
@Test
public void failedReconciliationRetainsIntentForRetry() throws Exception {
Fixture fixture = new Fixture();
fixture.write(new BlockPos(-31, 5, 49), Blocks.COMPOSTER.defaultBlockState());
IllegalStateException failure = new IllegalStateException("POI storage failure");
doThrow(failure).when(fixture.manager).add(any(), any());
onOwner(() -> assertSame(failure, assertThrows(IllegalStateException.class,
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded))));
assertArrayEquals(new long[]{16L}, fixture.marker());
fixture.allowPoiAdds();
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
}
@Test
public void explicitPoiSuppressionAndReadOnlyFullChunksDoNotCreateIntent() {
Fixture fixture = new Fixture();
BlockPos position = new BlockPos(-31, 5, 49);
fixture.updates.setBlock(fixture.world, position, Blocks.COMPOSTER.defaultBlockState(),
4096, 17);
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
ImposterProtoChunk full = mock(ImposterProtoChunk.class);
when(fixture.world.getChunk(any(BlockPos.class))).thenReturn(full);
fixture.updates.setBlock(fixture.world, position, Blocks.BARREL.defaultBlockState(), 2, 17);
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
}
@Test
public void invalidSectionBitsRetainTheStoredRecord() throws Exception {
Fixture fixture = new Fixture();
fixture.proto.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, new long[]{1L << 24});
onOwner(() -> assertThrows(IllegalArgumentException.class,
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded)));
assertArrayEquals(new long[]{1L << 24}, fixture.marker());
}
private static void onOwner(Runnable action) throws Exception {
FutureTask<Void> task = new FutureTask<>(action, null);
new TickThread(task, "Native POI test").start();
task.get(5L, TimeUnit.SECONDS);
}
private static PalettedContainerFactory containerFactory() {
Strategy<BlockState> blocks = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY);
BlockState air = Blocks.AIR.defaultBlockState();
IdMapper<Holder<Biome>> biomeIds = new IdMapper<>();
Holder<Biome> biome = Holder.direct((Biome) null);
biomeIds.add(biome);
Strategy<Holder<Biome>> biomes = Strategy.createForBiomes(biomeIds);
Codec<Holder<Biome>> biomeCodec = Codec.STRING.xmap(name -> biome, holder -> "iris-test-biome");
return new PalettedContainerFactory(blocks, air, PalettedContainer.codecRW(BlockState.CODEC, blocks, air),
biomes, biome, PalettedContainer.codecRO(biomeCodec, biomes, biome),
PalettedContainer.codecRW(biomeCodec, biomes, biome));
}
private static final class Fixture {
private final NativeStructurePoiUpdates updates = new NativeStructurePoiUpdates(4096);
private final ProtoChunk proto = new ProtoChunk(new ChunkPos(-2, 3), UpgradeData.EMPTY,
LevelHeightAccessor.create(-64, 384), containerFactory(), null);
private final LevelChunk loaded = mock(LevelChunk.class);
private final WorldGenLevel world = mock(WorldGenLevel.class);
private final PoiManager manager = mock(PoiManager.class);
private final Map<Long, PoiSection> pois = new HashMap<>();
private Fixture() {
ServerLevel level = mock(ServerLevel.class);
when(level.getPoiManager()).thenReturn(manager);
loaded.persistentDataContainer = proto.persistentDataContainer;
when(loaded.getLevel()).thenReturn(level);
when(loaded.getPos()).thenReturn(proto.getPos());
when(loaded.getSectionsCount()).thenReturn(proto.getSectionsCount());
when(loaded.getSectionYFromSectionIndex(anyInt())).thenAnswer(call -> proto.getSectionYFromSectionIndex(call.getArgument(0)));
when(loaded.getSection(anyInt())).thenAnswer(call -> proto.getSection(call.getArgument(0)));
when(loaded.getBlockState(any())).thenAnswer(call -> proto.getBlockState(call.getArgument(0)));
when(world.getChunk(any(BlockPos.class))).thenReturn(proto);
when(world.setBlock(any(), any(), anyInt(), anyInt())).thenAnswer(call -> {
proto.setBlockState(call.getArgument(0), call.getArgument(1), call.getArgument(2));
return true;
});
when(manager.getOrLoad(anyLong())).thenAnswer(call -> Optional.ofNullable(pois.get((long) call.getArgument(0))));
when(manager.getType(any())).thenAnswer(call -> {
BlockPos position = call.getArgument(0);
PoiSection section = pois.get(SectionPos.of(position).asLong());
return section == null ? Optional.empty() : section.getType(position);
});
doAnswer(call -> {
BlockPos position = call.getArgument(0);
pois.get(SectionPos.of(position).asLong()).remove(position);
return null;
}).when(manager).remove(any());
allowPoiAdds();
}
private void allowPoiAdds() {
doAnswer(call -> {
BlockPos position = call.getArgument(0);
return pois.computeIfAbsent(SectionPos.of(position).asLong(), ignored -> new PoiSection(() -> {}))
.add(position, call.getArgument(1));
}).when(manager).add(any(), any());
}
private void write(BlockPos position, BlockState state) {
updates.setBlock(world, position, state, Block.UPDATE_CLIENTS, Block.UPDATE_LIMIT);
}
private long[] marker() {
return proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
}
private PoiSection records() {
return pois.get(SectionPos.of(new BlockPos(-31, 5, 49)).asLong());
}
}
}
@@ -53,6 +53,7 @@ import art.arcane.iris.core.link.IrisPapiListener;
import art.arcane.iris.core.link.IrisPapiState;
import art.arcane.iris.core.localization.IrisLanguage;
import art.arcane.iris.core.link.MultiverseCoreLink;
import art.arcane.iris.core.agent.AttachSignal;
import art.arcane.iris.core.nms.INMS;
import art.arcane.iris.core.gui.BukkitGuiHost;
import art.arcane.iris.core.gui.PregeneratorJob;
@@ -203,7 +204,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
private final PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this);
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
private volatile SettingsHotloadWatch settingsHotloadWatch;
private volatile Thread serverLifecycleThread;
public static VolmitSender getSender() {
VolmitSender current = sender;
@@ -540,6 +540,17 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
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) {
@@ -746,7 +757,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
public void addShutdownHook() {
removeShutdownHook();
serverLifecycleThread = Thread.currentThread();
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
try {
Runtime.getRuntime().addShutdownHook(shutdownHook);
@@ -877,6 +887,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
}
public void onDisable() {
pendingWorldReplacements.awaitStagingForShutdown();
teardownPapi();
boolean serverStopping = IrisToolbelt.isServerStopping();
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
@@ -1012,7 +1023,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
if (generator == null) {
continue;
}
IrisToolbelt.beginWorldMaintenance(world, reason, true);
IrisToolbelt.beginWorldMaintenance(world, reason);
if (!deferredShutdownGenerators.contains(generator)) {
deferredShutdownGenerators.add(generator);
}
@@ -1024,51 +1035,31 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
if (!postStopFinisherStarted.compareAndSet(false, true)) {
return;
}
Thread activeServerThread = serverLifecycleThread;
if (activeServerThread == null) {
Iris.warn("Iris could not start its post-stop runtime finisher because the server lifecycle thread is unavailable.");
return;
}
Thread finisher = new Thread(() -> {
if (!awaitServerThreadTermination(activeServerThread)) {
return;
}
finishDeferredRuntimeTeardown("post-server-stop", 30L);
}, "Iris-PostStop-Finisher");
Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"),
"Iris-PostStop-Finisher");
finisher.setDaemon(false);
finisher.start();
}
static boolean awaitServerThreadTermination(Thread serverThread) {
if (serverThread == null || serverThread == Thread.currentThread()) {
return false;
}
try {
serverThread.join();
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
Iris.reportError("Iris post-stop runtime finisher was interrupted.", e);
return false;
}
}
private void runShutdownHook() {
if (startupBoundaryRestart.get()) {
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
return;
}
finishRuntimeAfterServerShutdown("shutdown-hook");
}
private void finishRuntimeAfterServerShutdown(String reason) {
if (!awaitServerShutdownBoundary()) {
Iris.warn("Iris skipped JVM-hook runtime teardown because Paper did not reach its post-world-close boundary.");
Iris.warn("Iris retained its runtime and plugin class loader because the server did not reach its post-world-close boundary.");
return;
}
finishDeferredRuntimeTeardown("shutdown-hook", 30L);
finishDeferredRuntimeTeardown(reason, 30L);
}
private boolean awaitServerShutdownBoundary() {
if (!INMS.isBound()) {
return true;
return false;
}
try {
return INMS.get().awaitServerShutdownBoundary(
@@ -1281,12 +1272,15 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
public int getIrisVersion() {
String input = getDescription().getVersion();
int hyphenIndex = input.indexOf('-');
if (hyphenIndex != -1) {
String result = input.substring(0, hyphenIndex);
result = result.replaceAll("\\.", "");
return Integer.parseInt(result);
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;
}
return -1;
}
public int getMCVersion() {
@@ -55,6 +55,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@@ -73,6 +74,9 @@ public final class PendingWorldReplacementManager implements Listener {
private volatile UUID overworldEntryAwaitingVerification;
private volatile World overworldEntryWorld;
private volatile boolean paperEntryListenerRegistered;
private final Object stagingMonitor = new Object();
private boolean stagingAdmissionOpen = true;
private StagingAdmission activeStaging;
public PendingWorldReplacementManager(Iris plugin) {
this.plugin = Objects.requireNonNull(plugin, "plugin");
@@ -135,7 +139,7 @@ public final class PendingWorldReplacementManager implements Listener {
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
requiredWorldKey.toString()
)) {
); StagingAdmission stagingAdmission = admitStaging(requiredWorldKey)) {
if (findTransaction(requiredWorldSlotKey) != null) {
throw new IOException("A replacement is already pending for " + requiredWorldKey + ".");
}
@@ -251,6 +255,29 @@ public final class PendingWorldReplacementManager implements Listener {
}
}
public void awaitStagingForShutdown() {
StagingAdmission staging;
synchronized (stagingMonitor) {
stagingAdmissionOpen = false;
staging = activeStaging;
}
if (staging == null) {
return;
}
Iris.warn("Waiting for the replacement of " + staging.worldKey + " to finish staging before Iris shuts down.");
boolean interrupted = false;
while (staging.finished.getCount() > 0L) {
try {
staging.finished.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
public synchronized void processPendingStartupReplacements() {
ArrayList<String> failures = new ArrayList<>();
ArrayList<String> restartBoundaries = new ArrayList<>();
@@ -993,6 +1020,17 @@ public final class PendingWorldReplacementManager implements Listener {
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
}
StagingAdmission admitStaging(NamespacedKey worldKey) throws IOException {
synchronized (stagingMonitor) {
if (!stagingAdmissionOpen) {
throw new IOException("Iris is shutting down. Run the replacement again after the server starts.");
}
StagingAdmission staging = new StagingAdmission(worldKey);
activeStaging = staging;
return staging;
}
}
private synchronized void loadOverworldEntryGuard() throws IOException {
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
@@ -1157,6 +1195,25 @@ public final class PendingWorldReplacementManager implements Listener {
}
}
final class StagingAdmission implements AutoCloseable {
private final NamespacedKey worldKey;
private final CountDownLatch finished = new CountDownLatch(1);
private StagingAdmission(NamespacedKey worldKey) {
this.worldKey = worldKey;
}
@Override
public void close() {
synchronized (stagingMonitor) {
if (activeStaging == this) {
activeStaging = null;
}
}
finished.countDown();
}
}
private static final class RestartBoundaryRequired extends IOException {
private RestartBoundaryRequired(String message) {
super(message);
@@ -0,0 +1,50 @@
package art.arcane.iris.core.agent;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
public final class AttachSignal {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static final long SIG_IGN = 1L;
private AttachSignal() {
}
public static boolean restoreJvmHandler() {
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
return false;
}
Linker linker = Linker.nativeLinker();
MethodHandle sigaction = linker.downcallHandle(
linker.defaultLookup().find("sigaction")
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment jvm = arena.allocate(ACTION_BYTES);
MemorySegment quit = arena.allocate(ACTION_BYTES);
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
}
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
return false;
}
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
}
return true;
} catch (RuntimeException | Error failure) {
throw failure;
} catch (Throwable failure) {
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
}
}
}
@@ -510,7 +510,7 @@ public class CommandIris implements DirectorExecutor {
return;
}
PlatformChunkGenerator generator = IrisToolbelt.access(world);
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
try {
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
@@ -522,6 +522,8 @@ public class CommandIris implements DirectorExecutor {
if (!Boolean.TRUE.equals(evacuated)) {
return CompletableFuture.completedFuture(false);
}
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
maintenanceEntered.set(true);
return WorldLifecycleService.get().unloadAsync(world, true);
})
.thenCompose(unloaded -> {
@@ -536,7 +538,9 @@ public class CommandIris implements DirectorExecutor {
});
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
.whenComplete((unloaded, throwable) -> {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
if (maintenanceEntered.get()) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
}
lease.close();
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
@@ -545,7 +549,9 @@ public class CommandIris implements DirectorExecutor {
J.s(response);
});
} catch (Exception e) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
if (maintenanceEntered.get()) {
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
}
lease.close();
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_FAILED_UNLOAD_WORLD_3, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
Iris.reportError("Failed to unload world \"" + world.getName() + "\".", e);
@@ -24,9 +24,10 @@ public class IrisShutdownOrderingTest {
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
String shutdownHook = section(source, "private void runShutdownHook()", "private boolean awaitServerShutdownBoundary");
String finisher = section(source, "private void startPostStopFinisher()", "static boolean awaitServerThreadTermination");
String serverJoin = section(source, "static boolean awaitServerThreadTermination", "private void runShutdownHook");
String shutdownHook = section(source, "private void runShutdownHook()", "private void finishRuntimeAfterServerShutdown");
String boundaryFinish = section(source, "private void finishRuntimeAfterServerShutdown", "private boolean awaitServerShutdownBoundary");
String boundaryAwait = section(source, "private boolean awaitServerShutdownBoundary", "private void finishDeferredRuntimeTeardown");
String finisher = section(source, "private void startPostStopFinisher()", "private void runShutdownHook");
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
String generatorQuiesce = section(generatorSource,
"public void quiesceForServerShutdown()", "public boolean isStudio()");
@@ -43,17 +44,19 @@ public class IrisShutdownOrderingTest {
"startupBoundaryRestart.get()",
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
"return;",
"awaitServerShutdownBoundary()",
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
"finishRuntimeAfterServerShutdown(\"shutdown-hook\")");
assertOrdered(finisher,
"finishRuntimeAfterServerShutdown(\"post-server-stop\")",
"finisher.setDaemon(false)",
"finisher.start()");
assertOrdered(finisher,
"awaitServerThreadTermination(activeServerThread)",
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
assertOrdered(serverJoin,
"serverThread == Thread.currentThread()",
"serverThread.join()");
assertOrdered(boundaryFinish,
"awaitServerShutdownBoundary()",
"return;",
"finishDeferredRuntimeTeardown(reason, 30L)");
assertTrue("A missing shutdown boundary must retain the runtime",
boundaryAwait.contains("if (!INMS.isBound()) {\n return false;"));
assertFalse("Runtime cleanup must wait for the shutdown boundary, not the server thread",
source.contains("serverThread.join()") || source.contains("serverLifecycleThread"));
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
quiesce.contains("generator.quiesceForServerShutdown()"));
assertOrdered(quiesce,
@@ -63,6 +66,12 @@ public class IrisShutdownOrderingTest {
assertOrdered(onDisable,
"quiesceRuntimeForServerShutdown(\"onDisable\")",
"super.onDisable()");
assertTrue("Server-stop quiescence must keep queued generation running its mantle stages",
quiesce.contains("IrisToolbelt.beginWorldMaintenance(world, reason);"));
assertTrue("Disable must wait for a replacement that is staging before it tears anything down",
onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()") >= 0
&& onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()")
< onDisable.indexOf("teardownPapi()"));
assertFalse("Server-stop quiescence must not begin generator close before Paper's boundary",
generatorQuiesce.contains("closing = true"));
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
@@ -0,0 +1,48 @@
package art.arcane.iris;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.Test;
import java.io.InputStream;
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;
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());
}
}
@Test
public void processedPluginMetadataProvidesAValidEngineVersion() throws Exception {
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
assertNotNull(stream);
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
doReturn(new PluginDescriptionFile(stream)).when(plugin).getDescription();
assertNotEquals(-1, plugin.getIrisVersion());
}
}
@Test
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());
}
}
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;
}
}
@@ -0,0 +1,70 @@
package art.arcane.iris.core;
import art.arcane.iris.Iris;
import org.bukkit.NamespacedKey;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class PendingWorldReplacementAdmissionTest {
private static final long STATE_TIMEOUT_SECONDS = 5L;
private static final long JOIN_TIMEOUT_SECONDS = 10L;
private static final long STATE_POLL_MILLIS = 5L;
private final NamespacedKey worldKey = NamespacedKey.minecraft("overworld");
@Test
public void shutdownDoesNotWaitWhenNothingIsStaging() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
shutdown.start();
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
assertFalse(shutdown.isAlive());
}
@Test
public void shutdownRejectsReplacementsThatStartAfterIt() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
manager.awaitStagingForShutdown();
IOException rejected = assertThrows(IOException.class, () -> manager.admitStaging(worldKey));
assertTrue(rejected.getMessage().contains("shutting down"));
}
@Test
public void shutdownWaitsForTheReplacementBeingStaged() throws Exception {
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
PendingWorldReplacementManager.StagingAdmission staging = manager.admitStaging(worldKey);
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
shutdown.start();
try {
awaitState(shutdown, Thread.State.WAITING);
assertTrue(shutdown.isAlive());
} finally {
staging.close();
}
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
assertFalse(shutdown.isAlive());
}
private static void awaitState(Thread thread, Thread.State state) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(STATE_TIMEOUT_SECONDS);
while (thread.getState() != state) {
if (System.nanoTime() > deadline) {
throw new AssertionError(thread.getName() + " never reached " + state + "; it is " + thread.getState());
}
Thread.sleep(STATE_POLL_MILLIS);
}
}
}
@@ -0,0 +1,57 @@
package art.arcane.iris.core.agent;
import org.junit.Test;
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
public class AttachSignalTest {
private static final int SIGQUIT = 3;
private static final int SIGTERM = 15;
private static final long ACTION_BYTES = 256;
private static final MethodHandle SIGACTION = Linker.nativeLinker().downcallHandle(
Linker.nativeLinker().defaultLookup().find("sigaction").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
@Test
public void aConsoleThatResetsQuitGetsTheJvmHandlerBack() throws Throwable {
assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"));
long jvmHandler = handler(SIGTERM);
assertNotEquals(0L, jvmHandler);
try (Arena arena = Arena.ofConfined()) {
MemorySegment original = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, MemorySegment.NULL, original));
try {
MemorySegment reset = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, reset, MemorySegment.NULL));
assertEquals(0L, handler(SIGQUIT));
assertTrue(AttachSignal.restoreJvmHandler());
assertEquals(jvmHandler, handler(SIGQUIT));
assertFalse(AttachSignal.restoreJvmHandler());
} finally {
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, original, MemorySegment.NULL));
}
}
}
private static long handler(int signal) throws Throwable {
try (Arena arena = Arena.ofConfined()) {
MemorySegment action = arena.allocate(ACTION_BYTES);
assertEquals(0, (int) SIGACTION.invokeExact(signal, MemorySegment.NULL, action));
return action.get(ValueLayout.JAVA_LONG, 0);
}
}
}
@@ -85,7 +85,7 @@ public class IrisPapiLifecycleTest {
String source = source();
assertTrue("onDisable must tear the expansion down",
source.contains("public void onDisable() {\n teardownPapi();"));
source.contains("public void onDisable() {\n pendingWorldReplacements.awaitStagingForShutdown();\n teardownPapi();"));
assertTrue("the BileTools pre-unload hook must tear the expansion down",
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
}
@@ -60,6 +60,7 @@ public final class IrisFabricBootstrap implements ModInitializer {
ServerLifecycleEvents.SERVER_STARTING.register((MinecraftServer server) -> ModdedEngineBootstrap.start(server));
ServerLifecycleEvents.SERVER_STARTED.register((MinecraftServer server) -> ModdedEngineBootstrap.serverStarted(server));
ServerLifecycleEvents.SERVER_STOPPING.register((MinecraftServer server) -> ModdedEngineBootstrap.stop());
ServerLifecycleEvents.SERVER_STOPPED.register((MinecraftServer server) -> ModdedEngineBootstrap.stopped());
ServerLevelEvents.LOAD.register((MinecraftServer server, ServerLevel level) -> ModdedEngineBootstrap.levelLoaded(level));
ServerLevelEvents.UNLOAD.register((MinecraftServer server, ServerLevel level) -> ModdedEngineBootstrap.levelUnloaded(level));
CommandRegistrationCallback.EVENT.register((CommandDispatcher<CommandSourceStack> dispatcher, CommandBuildContext buildContext, Commands.CommandSelection selection) -> IrisModdedCommands.register(dispatcher));
@@ -41,6 +41,7 @@ import net.minecraftforge.event.level.LevelEvent;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.event.server.ServerStartedEvent;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.event.server.ServerStoppedEvent;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.loot.IGlobalLootModifier;
@@ -82,6 +83,7 @@ public final class IrisForgeBootstrap {
ServerStartingEvent.BUS.addListener((ServerStartingEvent event) -> ModdedEngineBootstrap.start(event.getServer()));
ServerStartedEvent.BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
ServerStoppingEvent.BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
ServerStoppedEvent.BUS.addListener((ServerStoppedEvent event) -> ModdedEngineBootstrap.stopped());
LevelEvent.Load.BUS.addListener((LevelEvent.Load event) -> {
if (event.getLevel() instanceof ServerLevel level) {
ModdedEngineBootstrap.levelLoaded(level);
@@ -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<>();
@@ -52,6 +52,7 @@ import net.neoforged.neoforge.event.level.block.BreakBlockEvent;
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
import net.neoforged.neoforge.event.server.ServerStartedEvent;
import net.neoforged.neoforge.event.server.ServerStartingEvent;
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import net.neoforged.neoforge.registries.DeferredRegister;
@@ -84,6 +85,7 @@ public final class IrisNeoForgeBootstrap {
NeoForge.EVENT_BUS.addListener((ServerStartingEvent event) -> ModdedEngineBootstrap.start(event.getServer()));
NeoForge.EVENT_BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
NeoForge.EVENT_BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
NeoForge.EVENT_BUS.addListener((ServerStoppedEvent event) -> ModdedEngineBootstrap.stopped());
NeoForge.EVENT_BUS.addListener((LevelEvent.Load event) -> {
if (event.getLevel() instanceof ServerLevel level) {
ModdedEngineBootstrap.levelLoaded(level);