diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java index f6496ca1e..69ce5ccc1 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java @@ -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 { diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdates.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdates.java new file mode 100644 index 000000000..9b4c907b9 --- /dev/null +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdates.java @@ -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 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> 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()); + } + } + } + } + } +} diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructureWorldgenAccess.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructureWorldgenAccess.java index 0aa7271a6..36867eac2 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructureWorldgenAccess.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructureWorldgenAccess.java @@ -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()); diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdatesTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdatesTest.java new file mode 100644 index 000000000..5ab44d916 --- /dev/null +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NativeStructurePoiUpdatesTest.java @@ -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 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 task = new FutureTask<>(action, null); + new TickThread(task, "Native POI test").start(); + task.get(5L, TimeUnit.SECONDS); + } + + private static PalettedContainerFactory containerFactory() { + Strategy blocks = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY); + BlockState air = Blocks.AIR.defaultBlockState(); + IdMapper> biomeIds = new IdMapper<>(); + Holder biome = Holder.direct((Biome) null); + biomeIds.add(biome); + Strategy> biomes = Strategy.createForBiomes(biomeIds); + Codec> 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 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()); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java index 20e1757c8..b25013e61 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java @@ -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() { diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java index 0cde80b27..c7c0384e0 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/PendingWorldReplacementManager.java @@ -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 failures = new ArrayList<>(); ArrayList 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 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); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/agent/AttachSignal.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/agent/AttachSignal.java new file mode 100644 index 000000000..b7d209dfc --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/agent/AttachSignal.java @@ -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); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java index 8323a81a9..25044bc87 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java @@ -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 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); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java index d6b38919e..c12300f44 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java @@ -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", diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java new file mode 100644 index 000000000..44deb0d2d --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisVersionNumberTest.java @@ -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; + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/PendingWorldReplacementAdmissionTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/PendingWorldReplacementAdmissionTest.java new file mode 100644 index 000000000..a10a6c2c6 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/PendingWorldReplacementAdmissionTest.java @@ -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); + } + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/agent/AttachSignalTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/agent/AttachSignalTest.java new file mode 100644 index 000000000..dafe85db5 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/agent/AttachSignalTest.java @@ -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); + } + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/link/IrisPapiLifecycleTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/link/IrisPapiLifecycleTest.java index 193e614fa..03d5cf792 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/link/IrisPapiLifecycleTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/link/IrisPapiLifecycleTest.java @@ -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();")); } diff --git a/adapters/fabric/src/main/java/art/arcane/iris/fabric/IrisFabricBootstrap.java b/adapters/fabric/src/main/java/art/arcane/iris/fabric/IrisFabricBootstrap.java index 357e26a91..ae09a7e25 100644 --- a/adapters/fabric/src/main/java/art/arcane/iris/fabric/IrisFabricBootstrap.java +++ b/adapters/fabric/src/main/java/art/arcane/iris/fabric/IrisFabricBootstrap.java @@ -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 dispatcher, CommandBuildContext buildContext, Commands.CommandSelection selection) -> IrisModdedCommands.register(dispatcher)); diff --git a/adapters/forge/src/main/java/art/arcane/iris/forge/IrisForgeBootstrap.java b/adapters/forge/src/main/java/art/arcane/iris/forge/IrisForgeBootstrap.java index 253a01690..b1b9bd226 100644 --- a/adapters/forge/src/main/java/art/arcane/iris/forge/IrisForgeBootstrap.java +++ b/adapters/forge/src/main/java/art/arcane/iris/forge/IrisForgeBootstrap.java @@ -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); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java index 134939c0a..29a3d3638 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java @@ -65,7 +65,6 @@ public final class ModdedDimensionManager { private static final ConcurrentHashMap 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 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 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) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java index 4e7d62496..a9c441d47 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java @@ -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); } } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedPrimaryWorldRouter.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedPrimaryWorldRouter.java index 057489797..32ebb5d66 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedPrimaryWorldRouter.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedPrimaryWorldRouter.java @@ -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) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedScheduler.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedScheduler.java index 76ffee8e9..88f6bee49 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedScheduler.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedScheduler.java @@ -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(); } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedTeleportDeadline.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedTeleportDeadline.java new file mode 100644 index 000000000..250ab51cb --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedTeleportDeadline.java @@ -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 . + */ + +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); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldEngines.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldEngines.java index db771fbbb..ed2026986 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldEngines.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedWorldEngines.java @@ -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 { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/IrisModdedCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/IrisModdedCommands.java index 3230a76ca..5231cc8ad 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/IrisModdedCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/IrisModdedCommands.java @@ -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; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedVisionOverlay.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedVisionOverlay.java index a82c94522..e4f59f88c 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedVisionOverlay.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedVisionOverlay.java @@ -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) { diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java index 0f8d31ecf..b1529bfe5 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/service/ModdedChunkUpdateService.java @@ -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 chunk, Consumer3 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 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.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 chunk) { if (y < level.getMinY() || y >= level.getMaxY()) { return; diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEngineBootstrapShutdownTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEngineBootstrapShutdownTest.java new file mode 100644 index 000000000..2b544411b --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedEngineBootstrapShutdownTest.java @@ -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 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 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 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(); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedGenerationLeaseContractTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedGenerationLeaseContractTest.java index 404788225..787ba32a1 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedGenerationLeaseContractTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedGenerationLeaseContractTest.java @@ -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 diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLifecycleFailureContractTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLifecycleFailureContractTest.java index 662d1f557..cc716b673 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLifecycleFailureContractTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedLifecycleFailureContractTest.java @@ -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)"); diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedTeleportDeadlineTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedTeleportDeadlineTest.java new file mode 100644 index 000000000..060ef4cc7 --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/ModdedTeleportDeadlineTest.java @@ -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)); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandsTeleportTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandsTeleportTest.java new file mode 100644 index 000000000..ebbef52bc --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandsTeleportTest.java @@ -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)); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedWorldListingTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedWorldListingTest.java new file mode 100644 index 000000000..7e17ceefc --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedWorldListingTest.java @@ -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"); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceTest.java index 2e4b82df6..49f091c73 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/service/ModdedChunkUpdateServiceTest.java @@ -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 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 { + private final Matter section = new IrisMatter(16, 16, 16); + private final MatterSlice 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 void iterate(Class type, Consumer4 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 { private final ArrayList operations = new ArrayList<>(); diff --git a/adapters/neoforge/src/main/java/art/arcane/iris/neoforge/IrisNeoForgeBootstrap.java b/adapters/neoforge/src/main/java/art/arcane/iris/neoforge/IrisNeoForgeBootstrap.java index 687b40a91..026846a8b 100644 --- a/adapters/neoforge/src/main/java/art/arcane/iris/neoforge/IrisNeoForgeBootstrap.java +++ b/adapters/neoforge/src/main/java/art/arcane/iris/neoforge/IrisNeoForgeBootstrap.java @@ -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); diff --git a/build.gradle b/build.gradle index f0a331397..7159dd626 100644 --- a/build.gradle +++ b/build.gradle @@ -115,6 +115,7 @@ nmsBindings.each { key, value -> compileOnly(rootProject.libs.annotations) compileOnly(rootProject.libs.byteBuddy.core) testImplementation('junit:junit:4.13.2') + testImplementation('org.mockito:mockito-core:5.23.0') testImplementation(project(':core')) testCompileOnly(volmLibCoordinate) { transitive = false @@ -289,9 +290,10 @@ tasks.register('buildBukkit', Copy) { } } -// The three loader jars come out of nested standalone Gradle builds driven through Exec. Their own -// Gradle builds own the complete incremental model, so always launch them instead of allowing an -// incomplete outer input inventory to publish stale jars. +// The three loader jars come out of nested standalone Gradle builds driven through Exec. The outer +// task therefore has to carry the full inventory of what those builds read: every shared source tree, +// every build script and version file they load, and the local VolmLib checkout when the composite +// resolves one. Anything missing from that list publishes a stale jar. Closure resolveLocalVolmLibDirectory = { -> String configured = localVolmLibDirectory != null && !localVolmLibDirectory.isBlank() ? localVolmLibDirectory @@ -324,25 +326,48 @@ List moddedSharedInputs = [] 'adapters/client-common/src', 'core/src/main', 'core/build.gradle', + 'core/volmlib-left-out-of-bukkit-jar.txt', + 'core/agent/src', + 'core/agent/build.gradle', + 'api/api/src', + 'api/api/build.gradle.kts', + 'api/host/src', + 'api/host/build.gradle.kts', + 'api/build.gradle.kts', + 'api/settings.gradle.kts', 'module/src/main', 'module/build.gradle.kts', 'module/settings.gradle.kts', + 'module/gradle.properties', + 'module/lombok.config', 'module/builtin-modules.txt', 'spi/src/main', 'spi/build.gradle', 'build.gradle', 'settings.gradle', 'gradle.properties', + 'lombok.config', 'gradle/libs.versions.toml', - 'gradle/volmlib-resolution.settings.gradle' + 'gradle/volmlib-resolution.settings.gradle', + 'gradle/irisapi-resolution.settings.gradle' ].each { String path -> moddedSharedInputs.add(layout.projectDirectory.file(path).asFile) } File localVolmLibCheckout = useLocalVolmLib.equalsIgnoreCase('true') ? resolveLocalVolmLibDirectory() : null if (localVolmLibCheckout != null) { moddedSharedInputs.add(new File(localVolmLibCheckout, 'shared/src/main')) } +// The published VolmLib snapshot is resolved inside the nested build, so no outer input changes when it +// moves. Without a local checkout the Exec tasks always run and the nested build decides what is stale. +Closure rerunWhenVolmLibIsPublished = { Exec task -> + if (localVolmLibCheckout == null) { + task.outputs.upToDateWhen { false } + } + return null +} + Closure declareModdedJarIo = { Exec task, String adapter, String artifactName, Map versions -> task.inputs.files(moddedSharedInputs).withPropertyName('moddedSharedSources') + .withPathSensitivity(PathSensitivity.RELATIVE) task.inputs.files( layout.projectDirectory.file("adapters/${adapter}/src").asFile, layout.projectDirectory.file("adapters/${adapter}/build.gradle").asFile, @@ -351,10 +376,8 @@ Closure declareModdedJarIo = { Exec task, String adapter, String artifactN versions.each { String key, String value -> task.inputs.property(key, value) } task.inputs.property('useLocalVolmLib', useLocalVolmLib) task.inputs.property('volmLibCoordinate', volmLibCoordinate) - task.inputs.property('localVolmLibCheckout', localVolmLibCheckout == null ? '' : localVolmLibCheckout.absolutePath) task.outputs.file(layout.projectDirectory.file("adapters/${adapter}/build/libs/${artifactName}")) - task.outputs.upToDateWhen { false } - task.outputs.cacheIf { false } + rerunWhenVolmLibIsPublished(task) return null } @@ -372,8 +395,8 @@ tasks.register('fabricJar', Exec) { "-PuseLocalVolmLib=${useLocalVolmLib}", "-PvolmLibCoordinate=${volmLibCoordinate}" ] - if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) { - command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}") + if (localVolmLibCheckout != null) { + environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath) } commandLine(command) declareModdedJarIo(it, 'fabric', fabricArtifactName, [ @@ -410,8 +433,8 @@ tasks.register('forgeJar', Exec) { "-PuseLocalVolmLib=${useLocalVolmLib}", "-PvolmLibCoordinate=${volmLibCoordinate}" ] - if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) { - command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}") + if (localVolmLibCheckout != null) { + environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath) } commandLine(command) declareModdedJarIo(it, 'forge', forgeArtifactName, [ @@ -448,8 +471,8 @@ tasks.register('neoforgeJar', Exec) { "-PuseLocalVolmLib=${useLocalVolmLib}", "-PvolmLibCoordinate=${volmLibCoordinate}" ] - if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) { - command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}") + if (localVolmLibCheckout != null) { + environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath) } commandLine(command) declareModdedJarIo(it, 'neoforge', neoForgeArtifactName, [ @@ -486,6 +509,57 @@ tasks.named('neoforgeJar').configure { mustRunAfter(tasks.named('forgeJar')) } +// adapters/modded-common has no build of its own: its sources are compiled by each loader wrapper, so +// its tests only run when one of those wrappers is asked for `test`. The Fabric wrapper is the one +// that runs them as plain JUnit - NeoForge's moddev unit-test harness boots the mod through FML's +// transforming class loader and dies on a split-package ServiceConfigurationError before any test +// starts. One loader is enough: the sources are identical across all three. +tasks.register('moddedTest', Exec) { + group = 'verification' + description = 'Runs the adapters/modded-common test suite through the Fabric adapter build.' + workingDir = layout.projectDirectory.dir('adapters/fabric').asFile + String wrapperScript = System.getProperty('os.name').toLowerCase().contains('windows') ? 'gradlew.bat' : 'gradlew' + List command = [ + layout.projectDirectory.file(wrapperScript).asFile.absolutePath, + 'test', + '--console=plain', + "-PirisVersion=${project.version}", + "-PminecraftVersion=${minecraftVersion}", + "-PfabricLoaderVersion=${fabricLoaderVersion}", + "-PuseLocalVolmLib=${useLocalVolmLib}", + "-PvolmLibCoordinate=${volmLibCoordinate}" + ] + if (localVolmLibCheckout != null) { + environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath) + } + commandLine(command) + inputs.files(moddedSharedInputs).withPropertyName('moddedSharedSources') + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.files( + layout.projectDirectory.file('adapters/fabric/src').asFile, + layout.projectDirectory.file('adapters/fabric/build.gradle').asFile, + layout.projectDirectory.file('adapters/fabric/settings.gradle').asFile + ).withPropertyName('adapterSources') + inputs.property('irisVersion', project.version.toString()) + inputs.property('minecraftVersion', minecraftVersion) + inputs.property('fabricLoaderVersion', fabricLoaderVersion) + inputs.property('useLocalVolmLib', useLocalVolmLib) + inputs.property('volmLibCoordinate', volmLibCoordinate) + outputs.dir(layout.projectDirectory.dir('adapters/fabric/build/test-results/test')) + rerunWhenVolmLibIsPublished(it) + mustRunAfter(tasks.named('jar')) + mustRunAfter(project(':core').tasks.named('check')) + mustRunAfter(project(':spi').tasks.named('jar')) +} + +tasks.named('fabricJar').configure { + mustRunAfter(tasks.named('moddedTest')) +} + +tasks.named('check').configure { + dependsOn('moddedTest') +} + List commonModdedArtifactEntries = [ 'art/arcane/iris/engine/IrisEngine.class', 'art/arcane/iris/spi/IrisPlatform.class', diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index 2046a409d..0270c1deb 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -18,9 +18,16 @@ repositories { } } +// Nothing else asks buildSrc for `test`: Gradle only requests the jar that carries the build logic. +// Gating the jar on the tests is what makes them run at all, and it costs nothing once they are green. +tasks.named('jar').configure { + dependsOn(tasks.named('test')) +} + dependencies { implementation(gradleApi()) implementation('org.ow2.asm:asm:9.10.1') + implementation('org.apache.commons:commons-compress:1.28.0') implementation('com.github.VolmitSoftware:NMSTools:c88961416f') implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21') testImplementation('junit:junit:4.13.2') diff --git a/buildSrc/src/main/java/JarCompactor.java b/buildSrc/src/main/java/JarCompactor.java index 5ee5388b1..1906ea8fe 100644 --- a/buildSrc/src/main/java/JarCompactor.java +++ b/buildSrc/src/main/java/JarCompactor.java @@ -1,18 +1,22 @@ +import org.apache.commons.compress.archivers.zip.ExtraFieldUtils; +import org.apache.commons.compress.archivers.zip.Zip64Mode; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.gradle.api.GradleException; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.zip.CRC32; import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; +import java.util.zip.ZipFile; public final class JarCompactor { private static final int BUFFER_BYTES = 64 * 1024; @@ -45,31 +49,50 @@ public final class JarCompactor { private static void rewrite(Path source, Path destination) throws IOException { byte[] buffer = new byte[BUFFER_BYTES]; - try (InputStream rawInput = new BufferedInputStream(Files.newInputStream(source)); - ZipInputStream input = new ZipInputStream(rawInput); - OutputStream rawOutput = new BufferedOutputStream(Files.newOutputStream(destination)); - ZipOutputStream output = new ZipOutputStream(rawOutput)) { + try (ZipFile input = new ZipFile(source.toFile()); + ZipArchiveOutputStream output = new ZipArchiveOutputStream(destination)) { + if (!output.isSeekable()) { + throw new IOException("Jar compaction requires seekable output."); + } output.setLevel(9); - ZipEntry entry; - while ((entry = input.getNextEntry()) != null) { + output.setUseZip64(Zip64Mode.Never); + output.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NEVER); + Set names = new HashSet<>(); + Enumeration entries = input.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } - ZipEntry compacted = copyMetadata(entry); - output.putNextEntry(compacted); - int read; - while ((read = input.read(buffer)) >= 0) { - if (read > 0) { - output.write(buffer, 0, read); - } + if (!names.add(entry.getName())) { + throw new IOException("Duplicate jar entry: " + entry.getName()); } - output.closeEntry(); + output.putArchiveEntry(copyMetadata(entry)); + copyEntry(input, output, entry, buffer); + output.closeArchiveEntry(); } } } - private static ZipEntry copyMetadata(ZipEntry source) { - ZipEntry target = new ZipEntry(source.getName()); + private static void copyEntry(ZipFile input, ZipArchiveOutputStream output, ZipEntry entry, byte[] buffer) + throws IOException { + CRC32 crc = new CRC32(); + long size = 0L; + try (InputStream content = input.getInputStream(entry)) { + int read; + while ((read = content.read(buffer)) != -1) { + output.write(buffer, 0, read); + crc.update(buffer, 0, read); + size += read; + } + } + if (size != entry.getSize() || crc.getValue() != entry.getCrc()) { + throw new IOException("Jar entry failed size or CRC verification: " + entry.getName()); + } + } + + private static ZipArchiveEntry copyMetadata(ZipEntry source) throws IOException { + ZipArchiveEntry target = new ZipArchiveEntry(source.getName()); target.setMethod(ZipEntry.DEFLATED); if (source.getTime() >= 0L) { target.setTime(source.getTime()); @@ -78,7 +101,8 @@ public final class JarCompactor { target.setComment(source.getComment()); } if (source.getExtra() != null) { - target.setExtra(source.getExtra()); + target.setExtraFields(ExtraFieldUtils.parse(source.getExtra(), true, + ZipArchiveEntry.ExtraFieldParsingMode.BEST_EFFORT)); } return target; } diff --git a/buildSrc/src/test/java/JarCompactorTest.java b/buildSrc/src/test/java/JarCompactorTest.java index ffd5c2704..ac1763ded 100644 --- a/buildSrc/src/test/java/JarCompactorTest.java +++ b/buildSrc/src/test/java/JarCompactorTest.java @@ -1,16 +1,33 @@ +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.gradle.api.GradleException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.FileOutputStream; +import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.util.Enumeration; +import java.util.HexFormat; +import java.util.Map; +import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; +import java.util.zip.CRC32; +import java.util.zip.ZipEntry; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; public class JarCompactorTest { @Rule @@ -36,4 +53,128 @@ public class JarCompactorTest { jar.getJarEntry("example/value.txt")).readAllBytes()); } } + + @Test + public void preservesJarIdentityAndProducesDeterministicSeekableOutput() throws Exception { + File artifact = temporaryFolder.newFile("identity.jar"); + try (JarOutputStream output = new JarOutputStream(new FileOutputStream(artifact)); + InputStream classResource = getClass().getResourceAsStream("/JarCompactorTest.class")) { + output.setLevel(9); + writeEntry(output, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\r\nMulti-Release: true\r\n\r\n" + .getBytes(StandardCharsets.UTF_8)); + writeEntry(output, "JarCompactorTest.class", classResource.readAllBytes()); + writeEntry(output, "META-INF/iris/generation-kernels/abi-1.seal", "registry fixture".getBytes(StandardCharsets.UTF_8)); + writeEntry(output, "example/caf\u00e9.txt", "unicode name".getBytes(StandardCharsets.UTF_8)); + for (int index = 0; index < 100; index++) { + writeEntry(output, "example/item-" + index + ".txt", ("value-" + index).getBytes(StandardCharsets.UTF_8)); + } + } + Map original = identity(artifact); + long originalBytes = artifact.length(); + + JarCompactor.compact(artifact); + + assertEquals(original, identity(artifact)); + assertTrue(artifact.length() < originalBytes); + try (JarFile jar = new JarFile(artifact)) { + assertEquals("true", jar.getManifest().getMainAttributes().getValue("Multi-Release")); + assertEquals(0xCA, jar.getInputStream(jar.getJarEntry("JarCompactorTest.class")).read()); + } + try (ZipFile zip = ZipFile.builder().setFile(artifact).get()) { + Enumeration entries = zip.getEntries(); + while (entries.hasMoreElements()) { + assertFalse(entries.nextElement().getGeneralPurposeBit().usesDataDescriptor()); + } + } + byte[] first = Files.readAllBytes(artifact.toPath()); + JarCompactor.compact(artifact); + assertArrayEquals(first, Files.readAllBytes(artifact.toPath())); + } + + @Test + public void rejectsMalformedArchivesWithoutReplacingTheSource() throws Exception { + File artifact = temporaryFolder.newFile("invalid.jar"); + byte[] original = "not a zip archive".getBytes(StandardCharsets.UTF_8); + Files.write(artifact.toPath(), original); + + assertThrows(GradleException.class, () -> JarCompactor.compact(artifact)); + + assertArrayEquals(original, Files.readAllBytes(artifact.toPath())); + assertEquals(1, temporaryFolder.getRoot().listFiles().length); + } + + @Test + public void rejectsCorruptPayloadWithoutReplacingTheSource() throws Exception { + File artifact = temporaryFolder.newFile("corrupt.jar"); + byte[] payload = "checked-payload".getBytes(StandardCharsets.UTF_8); + CRC32 crc = new CRC32(); + crc.update(payload); + try (JarOutputStream output = new JarOutputStream(new FileOutputStream(artifact))) { + JarEntry entry = new JarEntry("value.txt"); + entry.setMethod(ZipEntry.STORED); + entry.setSize(payload.length); + entry.setCrc(crc.getValue()); + output.putNextEntry(entry); + output.write(payload); + output.closeEntry(); + } + byte[] corrupt = Files.readAllBytes(artifact.toPath()); + int payloadOffset = new String(corrupt, StandardCharsets.ISO_8859_1).indexOf("checked-payload"); + assertTrue(payloadOffset > 0); + corrupt[payloadOffset] ^= 1; + Files.write(artifact.toPath(), corrupt); + + assertThrows(GradleException.class, () -> JarCompactor.compact(artifact)); + + assertArrayEquals(corrupt, Files.readAllBytes(artifact.toPath())); + } + + @Test + public void rejectsDuplicateEntriesWithoutReplacingTheSource() throws Exception { + File artifact = temporaryFolder.newFile("duplicate.jar"); + try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(artifact)) { + for (int index = 0; index < 2; index++) { + output.putArchiveEntry(new ZipArchiveEntry("duplicate.txt")); + output.write(index); + output.closeArchiveEntry(); + } + } + byte[] original = Files.readAllBytes(artifact.toPath()); + + assertThrows(GradleException.class, () -> JarCompactor.compact(artifact)); + + assertArrayEquals(original, Files.readAllBytes(artifact.toPath())); + } + + private static void writeEntry(JarOutputStream output, String name, byte[] content) throws Exception { + JarEntry entry = new JarEntry(name); + entry.setTime(315_532_800_000L); + entry.setComment("preserved entry comment"); + entry.setExtra(new byte[]{(byte) 0xFE, (byte) 0xCA, 1, 0, 7}); + output.putNextEntry(entry); + output.write(content); + output.closeEntry(); + } + + private static Map identity(File artifact) throws Exception { + Map entries = new TreeMap<>(); + try (JarFile jar = new JarFile(artifact)) { + Enumeration contents = jar.entries(); + while (contents.hasMoreElements()) { + JarEntry entry = contents.nextElement(); + byte[] bytes; + try (InputStream input = jar.getInputStream(entry)) { + bytes = input.readAllBytes(); + } + entries.put(entry.getName(), new EntryIdentity( + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)), + entry.getSize(), entry.getCrc(), entry.getTime(), entry.getComment(), + entry.getExtra() == null ? "" : HexFormat.of().formatHex(entry.getExtra()))); + } + } + return entries; + } + + private record EntryIdentity(String sha256, long size, long crc, long time, String comment, String extra) { + } } diff --git a/core/src/main/java/art/arcane/iris/core/ServerConfigurator.java b/core/src/main/java/art/arcane/iris/core/ServerConfigurator.java index e11ae9b5d..25938a67e 100644 --- a/core/src/main/java/art/arcane/iris/core/ServerConfigurator.java +++ b/core/src/main/java/art/arcane/iris/core/ServerConfigurator.java @@ -46,7 +46,6 @@ import lombok.NonNull; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; @@ -92,6 +91,9 @@ public class ServerConfigurator { private static final String COMPILER_INPUT_FINGERPRINT_CACHE = "datapack-compiler-input-fingerprint"; static final String POST_COMPILE_RESTART_WARNING = "Iris installed updated datapack registry entries; " + "restart the server before creating worlds or opening Studios."; + private static final Path SPIGOT_CONFIGURATION = Path.of("spigot.yml"); + private static final Path PAPER_GLOBAL_CONFIGURATION = Path.of("config", "paper-global.yml"); + private static final String TIMEOUT_RECOVERY_FILE = "server-timeouts.json"; private static final int FINGERPRINT_BUFFER_BYTES = 64 * 1024; private static volatile boolean loadedDatapackRuntimeReady; private static volatile String loadedDatapackCompilerInputFingerprint = ""; @@ -108,11 +110,27 @@ public class ServerConfigurator { } IrisSettings.IrisSettingsAutoconfiguration s = IrisSettings.get().getAutoConfiguration(); if (s.isConfigureSpigotTimeoutTime()) { - J.attempt(ServerConfigurator::increaseKeepAliveSpigot); + Throwable failure = J.attemptCatch(ServerConfigurator::increaseKeepAliveSpigot); + if (failure != null) { + IrisLogging.reportError("Unable to persist the Spigot timeout setting.", failure); + } + } else { + Throwable failure = J.attemptCatch(() -> timeoutConfiguration().restore(ServerTimeoutConfiguration.SPIGOT_TIMEOUT_KEY)); + if (failure != null) { + IrisLogging.reportError("Unable to restore the Spigot timeout setting.", failure); + } } if (s.isConfigurePaperWatchdogDelay()) { - J.attempt(ServerConfigurator::increasePaperWatchdog); + Throwable failure = J.attemptCatch(ServerConfigurator::increasePaperWatchdog); + if (failure != null) { + IrisLogging.reportError("Unable to persist the Paper watchdog setting.", failure); + } + } else { + Throwable failure = J.attemptCatch(() -> timeoutConfiguration().restore(ServerTimeoutConfiguration.PAPER_WATCHDOG_KEY)); + if (failure != null) { + IrisLogging.reportError("Unable to restore the Paper watchdog setting.", failure); + } } if (DefaultPackBootstrapProvisioner.wasProvisionedThisStartup()) { @@ -240,34 +258,45 @@ public class ServerConfigurator { } private static void increaseKeepAliveSpigot() throws IOException, InvalidConfigurationException { - File spigotConfig = new File("spigot.yml"); - FileConfiguration f = new YamlConfiguration(); - f.load(spigotConfig); - long tt = f.getLong("settings.timeout-time"); + increaseKeepAliveSpigot(SPIGOT_CONFIGURATION, timeoutConfiguration()); + } - long spigotTimeout = TimeUnit.MINUTES.toSeconds(5); - - if (tt < spigotTimeout) { - IrisLogging.warn("Updating spigot.yml timeout-time: " + tt + " -> " + spigotTimeout + " (5 minutes)"); - IrisLogging.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value."); - f.set("settings.timeout-time", spigotTimeout); - f.save(spigotConfig); + static void increaseKeepAliveSpigot(Path file, ServerTimeoutConfiguration timeouts) throws IOException, InvalidConfigurationException { + long previous = loadConfiguration(file).getLong(ServerTimeoutConfiguration.SPIGOT_TIMEOUT_KEY); + long minimum = TimeUnit.MINUTES.toSeconds(5); + if (previous >= minimum) { + return; } + timeouts.raise(file, ServerTimeoutConfiguration.SPIGOT_TIMEOUT_KEY, minimum); + IrisLogging.warn("Updated " + file + " settings.timeout-time: " + previous + " -> " + minimum + + " seconds. Takes effect after a server restart."); + IrisLogging.warn("Disable autoConfiguration.configureSpigotTimeoutTime in iris.json to restore the original value."); } private static void increasePaperWatchdog() throws IOException, InvalidConfigurationException { - File spigotConfig = new File("config/paper-global.yml"); - FileConfiguration f = new YamlConfiguration(); - f.load(spigotConfig); - long tt = f.getLong("watchdog.early-warning-delay"); + increasePaperWatchdog(PAPER_GLOBAL_CONFIGURATION, timeoutConfiguration()); + } - long watchdog = TimeUnit.MINUTES.toMillis(3); - if (tt < watchdog) { - IrisLogging.warn("Updating paper.yml watchdog early-warning-delay: " + tt + " -> " + watchdog + " (3 minutes)"); - IrisLogging.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value."); - f.set("watchdog.early-warning-delay", watchdog); - f.save(spigotConfig); + static void increasePaperWatchdog(Path file, ServerTimeoutConfiguration timeouts) throws IOException, InvalidConfigurationException { + long previous = loadConfiguration(file).getLong(ServerTimeoutConfiguration.PAPER_WATCHDOG_KEY); + long minimum = TimeUnit.MINUTES.toMillis(3); + if (previous >= minimum) { + return; } + timeouts.raise(file, ServerTimeoutConfiguration.PAPER_WATCHDOG_KEY, minimum); + IrisLogging.warn("Updated " + file + " watchdog.early-warning-delay: " + previous + " -> " + minimum + + " milliseconds. Takes effect after a server restart."); + IrisLogging.warn("Disable autoConfiguration.configurePaperWatchdogDelay in iris.json to restore the original value."); + } + + private static YamlConfiguration loadConfiguration(Path file) throws IOException, InvalidConfigurationException { + YamlConfiguration configuration = new YamlConfiguration(); + configuration.load(file.toFile()); + return configuration; + } + + private static ServerTimeoutConfiguration timeoutConfiguration() { + return new ServerTimeoutConfiguration(IrisPlatforms.get().dataFolder().toPath().resolve(TIMEOUT_RECOVERY_FILE)); } public static KList getDatapacksFolder() { @@ -852,7 +881,7 @@ public class ServerConfigurator { private static void writeFingerprintCache(Path cacheFile, PackFingerprint fingerprint) { try { - writeFingerprintAtomic(cacheFile, fingerprint.content() + "\n" + fingerprint.metadata()); + writeStringAtomic(cacheFile, fingerprint.content() + "\n" + fingerprint.metadata()); } catch (IOException e) { IrisLogging.warn("Failed to write datapack fingerprint cache: " + e.getMessage()); } @@ -860,23 +889,23 @@ public class ServerConfigurator { private static void writeCompilerInputFingerprintCache(Path cacheFile, String fingerprint) { try { - writeFingerprintAtomic(cacheFile, fingerprint); + writeStringAtomic(cacheFile, fingerprint); } catch (IOException exception) { IrisLogging.warn("Failed to write datapack compiler-input fingerprint cache: " + exception.getMessage()); } } - private static void writeFingerprintAtomic(Path target, String fingerprint) throws IOException { + static void writeStringAtomic(Path target, String content) throws IOException { Path absoluteTarget = target.toAbsolutePath().normalize(); Path parent = absoluteTarget.getParent(); if (parent == null) { - throw new IOException("Datapack fingerprint target has no parent: " + absoluteTarget); + throw new IOException("Atomic write target has no parent: " + absoluteTarget); } Files.createDirectories(parent); - Path staged = Files.createTempFile(parent, ".datapack-fingerprint-", ".tmp"); + Path staged = Files.createTempFile(parent, ".iris-write-", ".tmp"); try { - Files.writeString(staged, fingerprint, StandardCharsets.UTF_8); + Files.writeString(staged, content, StandardCharsets.UTF_8); try (FileChannel channel = FileChannel.open(staged, StandardOpenOption.WRITE)) { channel.force(true); } diff --git a/core/src/main/java/art/arcane/iris/core/ServerTimeoutConfiguration.java b/core/src/main/java/art/arcane/iris/core/ServerTimeoutConfiguration.java new file mode 100644 index 000000000..88e860d39 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/ServerTimeoutConfiguration.java @@ -0,0 +1,143 @@ +package art.arcane.iris.core; + +import art.arcane.iris.spi.IrisLogging; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +final class ServerTimeoutConfiguration { + static final String SPIGOT_TIMEOUT_KEY = "settings.timeout-time"; + static final String PAPER_WATCHDOG_KEY = "watchdog.early-warning-delay"; + + private static final Object MUTATION_LOCK = new Object(); + private static final Gson JSON = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); + + private final Path recoveryFile; + + ServerTimeoutConfiguration(Path recoveryFile) { + this.recoveryFile = Objects.requireNonNull(recoveryFile); + } + + void raise(Path file, String key, long minimum) throws IOException { + synchronized (MUTATION_LOCK) { + Path target = file.toRealPath(); + YamlConfiguration configuration = load(target); + Long original = value(configuration, key); + List changes = readChanges(); + SavedTimeout saved = find(changes, target, key); + if (saved == null || !Objects.equals(original, saved.original()) && !Objects.equals(original, saved.applied())) { + changes.remove(saved); + changes.add(new SavedTimeout(target.toString(), key, original, minimum)); + writeChanges(changes); + } + configuration.set(key, minimum); + ServerConfigurator.writeStringAtomic(target, configuration.saveToString()); + } + } + + void restore(String key) throws IOException { + synchronized (MUTATION_LOCK) { + List changes = readChanges(); + for (SavedTimeout saved : List.copyOf(changes)) { + if (!saved.key().equals(key)) { + continue; + } + restore(saved); + changes.remove(saved); + writeChanges(changes); + } + } + } + + private void restore(SavedTimeout saved) throws IOException { + Path target = Path.of(saved.file()); + if (!Files.exists(target)) { + return; + } + YamlConfiguration configuration = load(target); + if (!Objects.equals(value(configuration, saved.key()), saved.applied())) { + IrisLogging.info("Kept the current " + target + " " + saved.key() + + " because it differs from the value saved by Iris."); + return; + } + configuration.set(saved.key(), saved.original()); + ServerConfigurator.writeStringAtomic(target, configuration.saveToString()); + IrisLogging.info("Restored " + target + " " + saved.key() + " to " + + (saved.original() == null ? "its server default" : saved.original()) + + ". Takes effect after a server restart."); + } + + private List readChanges() throws IOException { + if (!Files.exists(recoveryFile)) { + return new ArrayList<>(); + } + try { + SavedTimeouts saved = JSON.fromJson(Files.readString(recoveryFile), SavedTimeouts.class); + if (saved == null) { + throw new IOException("Empty server timeout recovery data: " + recoveryFile); + } + return new ArrayList<>(saved.changes()); + } catch (JsonParseException | IllegalArgumentException exception) { + throw new IOException("Invalid server timeout recovery data: " + recoveryFile, exception); + } + } + + private void writeChanges(List changes) throws IOException { + ServerConfigurator.writeStringAtomic(recoveryFile, JSON.toJson(new SavedTimeouts(changes))); + } + + private static SavedTimeout find(List changes, Path target, String key) { + for (SavedTimeout change : changes) { + if (change.file().equals(target.toString()) && change.key().equals(key)) { + return change; + } + } + return null; + } + + private static YamlConfiguration load(Path file) throws IOException { + YamlConfiguration configuration = new YamlConfiguration(); + try { + configuration.load(file.toFile()); + } catch (InvalidConfigurationException exception) { + throw new IOException("Invalid server configuration: " + file, exception); + } + return configuration; + } + + private static Long value(YamlConfiguration configuration, String key) throws IOException { + if (!configuration.isSet(key)) { + return null; + } + if (!configuration.isInt(key) && !configuration.isLong(key)) { + throw new IOException("Server timeout " + key + " must be an integer."); + } + return configuration.getLong(key); + } + + private record SavedTimeout(String file, String key, Long original, long applied) { + private SavedTimeout { + Objects.requireNonNull(file, "file"); + Objects.requireNonNull(key, "key"); + if (!Path.of(file).isAbsolute() || applied <= 0 + || !key.equals(SPIGOT_TIMEOUT_KEY) && !key.equals(PAPER_WATCHDOG_KEY)) { + throw new IllegalArgumentException("Invalid saved server timeout"); + } + } + } + + private record SavedTimeouts(List changes) { + private SavedTimeouts { + changes = List.copyOf(changes); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalService.java b/core/src/main/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalService.java index c45782a9a..685dbea6b 100644 --- a/core/src/main/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalService.java +++ b/core/src/main/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalService.java @@ -152,15 +152,19 @@ public final class IrisWorldRemovalService { boolean deleteFiles, AtomicBoolean terminal ) { + AtomicBoolean maintenanceEntered = new AtomicBoolean(false); CompletableFuture operation = phase( - RemovalStatus.RESOLUTION_FAILED, - () -> backend.beginMaintenance(resolved).thenApply(ignored -> resolved), + RemovalStatus.TELEPORT_FAILED, + () -> backend.evacuatePlayers(resolved).thenApply(ignored -> resolved), terminal ) .thenCompose(activeWorld -> phase( - RemovalStatus.TELEPORT_FAILED, - () -> backend.evacuatePlayers(activeWorld) - .thenApply(ignored -> activeWorld), + RemovalStatus.RESOLUTION_FAILED, + () -> { + CompletableFuture begun = backend.beginMaintenance(activeWorld); + maintenanceEntered.set(true); + return begun.thenApply(ignored -> activeWorld); + }, terminal )) .thenCompose(activeWorld -> phase( @@ -198,7 +202,7 @@ public final class IrisWorldRemovalService { ); })); - return operation.handle((result, throwable) -> backend.endMaintenance(resolved) + return operation.handle((result, throwable) -> endMaintenance(resolved, maintenanceEntered.get()) .handle((ignored, cleanupFailure) -> { if (cleanupFailure != null) { Throwable unwrappedCleanup = unwrap(cleanupFailure); @@ -216,6 +220,10 @@ public final class IrisWorldRemovalService { })).thenCompose(result -> result); } + private CompletableFuture endMaintenance(ResolvedWorld resolved, boolean entered) { + return entered ? backend.endMaintenance(resolved) : CompletableFuture.completedFuture(null); + } + private CompletableFuture validateResolvedWorld(ResolvedWorld resolvedWorld) { if (!resolvedWorld.managed()) { return CompletableFuture.failedFuture(new RemovalFailure( diff --git a/core/src/main/java/art/arcane/iris/core/localization/ModdedCommandMessages.java b/core/src/main/java/art/arcane/iris/core/localization/ModdedCommandMessages.java index 532e37912..95fed8d97 100644 --- a/core/src/main/java/art/arcane/iris/core/localization/ModdedCommandMessages.java +++ b/core/src/main/java/art/arcane/iris/core/localization/ModdedCommandMessages.java @@ -21,7 +21,10 @@ public final class ModdedCommandMessages { public static final TextKey IRIS_MODDED_COMMANDS_CONSOLE_MUST_NAME_PLAYER_IRIS_TP_DIMENSION_PLAYER = text("iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player"); public static final TextKey IRIS_MODDED_COMMANDS_IS_NOT_GENERATED_BY_IRIS = text("iris.modded.irismoddedcommands.is_not_generated_by_iris"); public static final TextKey IRIS_MODDED_COMMANDS_TELEPORT_FAILED_DIMENSION_IS_NOT_LOADED = text("iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded"); - public static final TextKey IRIS_MODDED_COMMANDS_TELEPORTING = text("iris.modded.irismoddedcommands.teleporting"); + public static final TextKey IRIS_MODDED_COMMANDS_TELEPORT_FAILED_REASON = text("iris.modded.irismoddedcommands.teleport_failed_reason"); + public static final TextKey IRIS_MODDED_COMMANDS_TELEPORT_CANCELLED_PLAYER_OFFLINE = text("iris.modded.irismoddedcommands.teleport_cancelled_player_offline"); + public static final TextKey IRIS_MODDED_COMMANDS_TELEPORT_REFUSED = text("iris.modded.irismoddedcommands.teleport_refused"); + public static final TextKey IRIS_MODDED_COMMANDS_TELEPORTING =text("iris.modded.irismoddedcommands.teleporting"); public static final TextKey IRIS_MODDED_COMMANDS_IS_NOT_GENERATED_BY_IRIS_2 = text("iris.modded.irismoddedcommands.is_not_generated_by_iris_2"); public static final TextKey IRIS_MODDED_COMMANDS_CANNOT_EVACUATE_PRIMARY_WORLD_THERE_IS_NOWHERE_SEND_PLAYERS = text("iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players"); public static final TextKey IRIS_MODDED_COMMANDS_EVACUATED_PLAYER_S_FROM = text("iris.modded.irismoddedcommands.evacuated_player_s_from"); diff --git a/core/src/main/java/art/arcane/iris/core/nms/INMSBinding.java b/core/src/main/java/art/arcane/iris/core/nms/INMSBinding.java index 32281d09c..d71692af8 100644 --- a/core/src/main/java/art/arcane/iris/core/nms/INMSBinding.java +++ b/core/src/main/java/art/arcane/iris/core/nms/INMSBinding.java @@ -230,6 +230,9 @@ public interface INMSBinding { default void flushChunkIO(World world) { } + default void reconcileNativeStructurePois(Chunk chunk) { + } + void injectBiomesFromMantle(Chunk e, Mantle mantle); ItemStack applyCustomNbt(ItemStack itemStack, KMap customNbt) throws IllegalArgumentException; diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java index 129be2571..35b523d05 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java @@ -485,12 +485,17 @@ public final class StudioOpenCoordinator { AtomicBoolean unloadStarted = new AtomicBoolean(false); AtomicBoolean folderDeleted = new AtomicBoolean(!deleteFolder); AtomicBoolean terminalTimeout = new AtomicBoolean(false); - if (world != null) { - IrisToolbelt.beginWorldMaintenance(world, "studio-close", true); - } + AtomicBoolean maintenanceEntered = new AtomicBoolean(false); CompletableFuture sequence = sequenceStudioClose( () -> evacuateWorldFamily(worldName, world), + () -> { + if (world == null) { + return; + } + IrisToolbelt.beginWorldMaintenance(world, "studio-close", true); + maintenanceEntered.set(true); + }, () -> { unloadStarted.set(true); return unloadWorldFamily(worldName, world).thenRun(() -> { @@ -535,7 +540,7 @@ public final class StudioOpenCoordinator { ); }); return operation.whenComplete((result, throwable) -> { - if (world != null) { + if (maintenanceEntered.get()) { IrisToolbelt.endWorldMaintenance(world, "studio-close", true); } }); @@ -549,22 +554,27 @@ public final class StudioOpenCoordinator { static CompletableFuture sequenceStudioClose( Supplier> evacuate, + Runnable enterMaintenance, Supplier> unload, Supplier> closeGenerator, Supplier> deleteFolders ) { - return sequenceStudioClose(evacuate, unload, closeGenerator, deleteFolders, () -> false); + return sequenceStudioClose(evacuate, enterMaintenance, unload, closeGenerator, deleteFolders, () -> false); } static CompletableFuture sequenceStudioClose( Supplier> evacuate, + Runnable enterMaintenance, Supplier> unload, Supplier> closeGenerator, Supplier> deleteFolders, BooleanSupplier terminalTimeout ) { return invokePhase(evacuate) - .thenCompose(ignored -> invokePhaseUnlessTimedOut(unload, terminalTimeout)) + .thenCompose(ignored -> invokePhaseUnlessTimedOut(() -> { + enterMaintenance.run(); + return unload.get(); + }, terminalTimeout)) .thenCompose(ignored -> invokePhaseUnlessTimedOut(closeGenerator, terminalTimeout)) .thenCompose(ignored -> invokePhaseUnlessTimedOut(deleteFolders, terminalTimeout)); } diff --git a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java index 679f8d785..85e00578f 100644 --- a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java @@ -845,12 +845,12 @@ public class StudioSVC implements IrisService { } private void destroyStudioWorld(World world, PlatformChunkGenerator generator) { - IrisToolbelt.beginWorldMaintenance(world, "studio-disable", true); try { IrisToolbelt.evacuate(world); } catch (Throwable e) { IrisLogging.reportError("Failed to evacuate studio world \"" + world.getName() + "\" during shutdown cleanup.", e); } + IrisToolbelt.beginWorldMaintenance(world, "studio-disable", true); try { WorldLifecycleService.get().unloadAsync(world, false) .thenCompose(unloaded -> { diff --git a/core/src/main/java/art/arcane/iris/core/tools/IrisCreator.java b/core/src/main/java/art/arcane/iris/core/tools/IrisCreator.java index 1169a3e11..d08c2f192 100644 --- a/core/src/main/java/art/arcane/iris/core/tools/IrisCreator.java +++ b/core/src/main/java/art/arcane/iris/core/tools/IrisCreator.java @@ -313,6 +313,8 @@ public class IrisCreator { .thenCompose(Function.identity()) .get(WORLD_CREATE_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!studio && !benchmark) { + World createdWorld = world; + J.sfut(() -> createdWorld.save()).get(WORLD_CREATE_TIMEOUT_SECONDS, TimeUnit.SECONDS); awaitInitialSpawnPreparation(access, name); } } catch (Throwable e) { @@ -745,12 +747,15 @@ public class IrisCreator { } } if (activeWorld != null) { - IrisToolbelt.beginWorldMaintenance(activeWorld, "world-create-rollback", true); + boolean maintenanceEntered = false; try { PlatformChunkGenerator generator = IrisToolbelt.access(activeWorld); boolean evacuated = Boolean.TRUE.equals(IrisToolbelt.evacuateAsync(activeWorld) .get(ROLLBACK_PHASE_TIMEOUT_SECONDS, TimeUnit.SECONDS)); - if (!evacuated) { + if (evacuated) { + IrisToolbelt.beginWorldMaintenance(activeWorld, "world-create-rollback", true); + maintenanceEntered = true; + } else { safeToDelete = false; failure.addSuppressed(new IllegalStateException( "Rollback could not evacuate world \"" + name + "\".")); @@ -778,7 +783,9 @@ public class IrisCreator { ServerConfigurator.restart("World creation rollback timed out for \"" + name + "\"."); } } finally { - IrisToolbelt.endWorldMaintenance(activeWorld, "world-create-rollback", true); + if (maintenanceEntered) { + IrisToolbelt.endWorldMaintenance(activeWorld, "world-create-rollback", true); + } } } diff --git a/core/src/main/java/art/arcane/iris/engine/IrisWorldManager.java b/core/src/main/java/art/arcane/iris/engine/IrisWorldManager.java index 59abe339c..0335ec567 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisWorldManager.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisWorldManager.java @@ -21,6 +21,7 @@ package art.arcane.iris.engine; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.core.IrisSettings; import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.iris.core.nms.INMS; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedWorldManager; import art.arcane.iris.spi.IrisLogging; @@ -205,6 +206,8 @@ public class IrisWorldManager extends EngineAssignedWorldManager { return; } + INMS.get().reconcileNativeStructurePois(e); + if (cleanupServiceStopped || cleanupService == null || cleanupService.isShutdown()) { return; } diff --git a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBiome.java b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBiome.java index 245ffe4a6..89800c39d 100644 --- a/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBiome.java +++ b/core/src/main/java/art/arcane/iris/platform/bukkit/BukkitBiome.java @@ -19,43 +19,33 @@ package art.arcane.iris.platform.bukkit; import art.arcane.iris.spi.PlatformBiome; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import org.bukkit.NamespacedKey; import org.bukkit.block.Biome; -import java.util.concurrent.ConcurrentHashMap; - /** * Interned Bukkit adapter for a neutral biome handle. */ public final class BukkitBiome implements PlatformBiome { - private static final ConcurrentHashMap CACHE = new ConcurrentHashMap<>(); + private static final Cache CACHE = Caffeine.newBuilder() + .weakKeys() + .maximumSize(4_096) + .build(); private final Biome biome; private final String key; private final String namespace; - private BukkitBiome(Biome biome, String key) { + private BukkitBiome(Biome biome) { this.biome = biome; - this.key = key; - int colon = key.indexOf(':'); - this.namespace = colon >= 0 ? key.substring(0, colon) : "minecraft"; + NamespacedKey biomeKey = biome.getKey(); + this.key = biomeKey.toString(); + this.namespace = biomeKey.getNamespace(); } public static BukkitBiome of(Biome biome) { - String key = biomeKey(biome); - return CACHE.computeIfAbsent(key, (String k) -> new BukkitBiome(biome, k)); - } - - private static String biomeKey(Biome biome) { - for (String method : new String[]{"getKeyOrNull", "getKeyOrThrow", "getKey"}) { - try { - Object key = Biome.class.getMethod(method).invoke(biome); - if (key != null) { - return key.toString(); - } - } catch (Throwable ignored) { - } - } - return biome.toString(); + return CACHE.get(biome, BukkitBiome::new); } @Override diff --git a/core/src/main/resources/languages/de_DE.json b/core/src/main/resources/languages/de_DE.json index 6c5c92b4b..1eb0c4dca 100644 --- a/core/src/main/resources/languages/de_DE.json +++ b/core/src/main/resources/languages/de_DE.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Die Konsole muss einen Spieler benennen: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} wird nicht von Iris generiert.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleportation fehlgeschlagen: Dimension {dimensionId} ist nicht geladen.", - "iris.modded.irismoddedcommands.teleporting": "Teleportiere {value} nach {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleport nach {dimensionId} fehlgeschlagen: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleport nach {dimensionId} abgebrochen: {value} ist nicht mehr online.", + "iris.modded.irismoddedcommands.teleport_refused": "Teleport nach {dimensionId} wurde vom Server abgelehnt.", + "iris.modded.irismoddedcommands.teleporting":"Teleportiere {value} nach {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} wird nicht von Iris generiert.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Die primäre Welt kann nicht evakuiert werden, da es kein Ziel für die Spieler gibt.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} Spieler von {value} nach {value2} evakuiert.", diff --git a/core/src/main/resources/languages/es_ES.json b/core/src/main/resources/languages/es_ES.json index 899fd6709..4a96f2ed4 100644 --- a/core/src/main/resources/languages/es_ES.json +++ b/core/src/main/resources/languages/es_ES.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La consola debe indicar un jugador: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} no se genera por Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "El teletransporte falló: la dimensión {dimensionId} no está cargada.", - "iris.modded.irismoddedcommands.teleporting": "Teletransportando a {value} a {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "El teletransporte a {dimensionId} falló: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teletransporte a {dimensionId} cancelado: {value} ya no está conectado.", + "iris.modded.irismoddedcommands.teleport_refused": "El servidor rechazó el teletransporte a {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Teletransportando a {value} a {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} no se genera por Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "No se puede evacuar el mundo principal porque no hay adónde enviar a los jugadores.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Se evacuaron {count} jugador(es) de {value} a {value2}.", diff --git a/core/src/main/resources/languages/fi_FI.json b/core/src/main/resources/languages/fi_FI.json index 4d4706770..6bc7d0dba 100644 --- a/core/src/main/resources/languages/fi_FI.json +++ b/core/src/main/resources/languages/fi_FI.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolin on nimettävä pelaaja: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} ei ole tuotettu Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleportti epäonnistui: ulottuvuus {dimensionId} ei ole ladattu.", - "iris.modded.irismoddedcommands.teleporting": "Telesiirtäminen {value} - {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleporttaus ulottuvuuteen {dimensionId} epäonnistui: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleporttaus ulottuvuuteen {dimensionId} peruttiin: {value} ei ole enää paikalla.", + "iris.modded.irismoddedcommands.teleport_refused": "Palvelin hylkäsi teleporttauksen ulottuvuuteen {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Telesiirtäminen {value} - {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} ei ole tuotettu Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Ensisijaista maailmaa ei voida evakuoida; pelaajia ei voi lähettää minnekään.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuoitu {count} pelaajat {value} - {value2}.", diff --git a/core/src/main/resources/languages/fr_FR.json b/core/src/main/resources/languages/fr_FR.json index 04a4b2cd3..8c876440d 100644 --- a/core/src/main/resources/languages/fr_FR.json +++ b/core/src/main/resources/languages/fr_FR.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console doit indiquer un joueur : /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} n'est pas généré par Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Échec de la téléportation : la dimension {dimensionId} n'est pas chargée.", - "iris.modded.irismoddedcommands.teleporting": "Téléportation de {value} vers {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Échec de la téléportation vers {dimensionId} : {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Téléportation vers {dimensionId} annulée : {value} n'est plus connecté.", + "iris.modded.irismoddedcommands.teleport_refused": "Le serveur a refusé la téléportation vers {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Téléportation de {value} vers {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} n'est pas généré par Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Impossible d'évacuer le monde principal, car aucun autre monde ne peut accueillir les joueurs.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} joueur(s) évacué(s) de {value} vers {value2}.", diff --git a/core/src/main/resources/languages/he_IL.json b/core/src/main/resources/languages/he_IL.json index 452bd5dc9..fe7e19569 100644 --- a/core/src/main/resources/languages/he_IL.json +++ b/core/src/main/resources/languages/he_IL.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "הקונסולה חייבת לקרוא לשחקן: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} לא נוצר על ידי Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "טלפורט נכשל: ממד {dimensionId} לא טעון.", - "iris.modded.irismoddedcommands.teleporting": "תקשורת {value} כדי {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "השיגור אל {dimensionId} נכשל: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "השיגור אל {dimensionId} בוטל: {value} כבר לא מחובר.", + "iris.modded.irismoddedcommands.teleport_refused": "השרת דחה את השיגור אל {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"תקשורת {value} כדי {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} לא נוצר על ידי Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "לא ניתן לפנות לעולם הראשי, אין מקום לשלוח שחקנים.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "הערכה {count} שחקן(s) {value} כדי {value2}.", diff --git a/core/src/main/resources/languages/it_IT.json b/core/src/main/resources/languages/it_IT.json index c2c627704..2f9d34e4a 100644 --- a/core/src/main/resources/languages/it_IT.json +++ b/core/src/main/resources/languages/it_IT.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console deve specificare un giocatore: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} non è generato da Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teletrasporto non riuscito: la dimensione {dimensionId} non è caricata.", - "iris.modded.irismoddedcommands.teleporting": "Teletrasporto di {value} verso {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teletrasporto verso {dimensionId} non riuscito: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teletrasporto verso {dimensionId} annullato: {value} non è più online.", + "iris.modded.irismoddedcommands.teleport_refused": "Il server ha rifiutato il teletrasporto verso {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Teletrasporto di {value} verso {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} non è generato da Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Impossibile evacuare il mondo principale: non esiste una destinazione per i giocatori.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuati {count} giocatori da {value} a {value2}.", diff --git a/core/src/main/resources/languages/ja-JP.json b/core/src/main/resources/languages/ja-JP.json index d95a32142..3af895dba 100644 --- a/core/src/main/resources/languages/ja-JP.json +++ b/core/src/main/resources/languages/ja-JP.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "コンソールではプレイヤーを指定してください: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} は Iris によって生成されていません。", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "テレポートに失敗しました: ディメンション {dimensionId} は読み込まれていません。", - "iris.modded.irismoddedcommands.teleporting": "{value} を {dimensionId} にテレポートしています...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "{dimensionId} へのテレポートに失敗しました: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "{dimensionId} へのテレポートを中止しました: {value} はオフラインです。", + "iris.modded.irismoddedcommands.teleport_refused": "サーバーが {dimensionId} へのテレポートを拒否しました。", + "iris.modded.irismoddedcommands.teleporting":"{value} を {dimensionId} にテレポートしています...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} は Iris によって生成されていません。", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "プライマリーワールドからは退避できません。プレイヤーの移動先がありません。", "iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} 人のプレイヤーを {value} から {value2} へ退避させました。", diff --git a/core/src/main/resources/languages/ko_KR.json b/core/src/main/resources/languages/ko_KR.json index d17811c3e..2fb5b822e 100644 --- a/core/src/main/resources/languages/ko_KR.json +++ b/core/src/main/resources/languages/ko_KR.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "콘솔은 플레이어를 지정해야 합니다: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 에 의해 생성되지 않음 Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 실패: 차원 {dimensionId} 로드 되지 않습니다.", - "iris.modded.irismoddedcommands.teleporting": "팟캐스트 {value} 으로 {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "{dimensionId}(으)로 순간이동 실패: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "{dimensionId}(으)로 순간이동 취소됨: {value} 님이 더 이상 접속해 있지 않습니다.", + "iris.modded.irismoddedcommands.teleport_refused": "서버가 {dimensionId}(으)로의 순간이동을 거부했습니다.", + "iris.modded.irismoddedcommands.teleporting":"팟캐스트 {value} 으로 {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} 에 의해 생성되지 않음 Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "1 차 세계를 피할 수 없습니다. 플레이어에게 보내는 곳이 없습니다.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "플레이어 {count}명을 {value}에서 {value2}(으)로 대피시켰습니다.", diff --git a/core/src/main/resources/languages/lt_LT.json b/core/src/main/resources/languages/lt_LT.json index bb880fdf5..8f0e6a4a0 100644 --- a/core/src/main/resources/languages/lt_LT.json +++ b/core/src/main/resources/languages/lt_LT.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolė turi pavadinti žaidėją: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} generuoja ne Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleportas nepavyko: dimensija {dimensionId} neįkrauta.", - "iris.modded.irismoddedcommands.teleporting": "Teleportavimas {value} iki {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleportavimas į {dimensionId} nepavyko: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleportavimas į {dimensionId} atšauktas: {value} nebėra prisijungęs.", + "iris.modded.irismoddedcommands.teleport_refused": "Serveris atmetė teleportavimą į {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Teleportavimas {value} iki {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} generuoja ne Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Negalima evakuoti pirminio pasaulio; nėra kur siųsti žaidėjų.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuoti {count} grotuvas (-ai) iš {value} iki {value2}.", diff --git a/core/src/main/resources/languages/nl_NL.json b/core/src/main/resources/languages/nl_NL.json index efc83c127..890b3e5f1 100644 --- a/core/src/main/resources/languages/nl_NL.json +++ b/core/src/main/resources/languages/nl_NL.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console moet een speler een naam geven: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} wordt niet gegenereerd door Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleporteren mislukt: dimensie {dimensionId} is niet geladen.", - "iris.modded.irismoddedcommands.teleporting": "Teleporteren {value} tot {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleporteren naar {dimensionId} mislukt: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleporteren naar {dimensionId} geannuleerd: {value} is niet meer online.", + "iris.modded.irismoddedcommands.teleport_refused": "De server heeft het teleporteren naar {dimensionId} geweigerd.", + "iris.modded.irismoddedcommands.teleporting":"Teleporteren {value} tot {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} wordt niet gegenereerd door Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Kan de primaire wereld niet evacueren; er is geen plek om spelers te sturen.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Ontruimd {count} speler(s) van {value} tot {value2}.", diff --git a/core/src/main/resources/languages/pl_PL.json b/core/src/main/resources/languages/pl_PL.json index 462374bd7..fddcc9ff4 100644 --- a/core/src/main/resources/languages/pl_PL.json +++ b/core/src/main/resources/languages/pl_PL.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsola musi nazwać gracza: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} nie jest generowany przez Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport nie powiódł się: wymiar {dimensionId} nie jest załadowany.", - "iris.modded.irismoddedcommands.teleporting": "Teleportowanie {value} do {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleportacja do {dimensionId} nie powiodła się: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleportacja do {dimensionId} anulowana: {value} nie jest już online.", + "iris.modded.irismoddedcommands.teleport_refused": "Serwer odrzucił teleportację do {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Teleportowanie {value} do {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} nie jest generowany przez Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Nie można ewakuować głównego świata; nie ma gdzie wysłać graczy.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Ewakuowane {count} odtwarzacz (-i) z {value} do {value2}.", diff --git a/core/src/main/resources/languages/pt_PT.json b/core/src/main/resources/languages/pt_PT.json index 455cc38f1..16b7261d7 100644 --- a/core/src/main/resources/languages/pt_PT.json +++ b/core/src/main/resources/languages/pt_PT.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "A consola deve nomear um jogador: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} não é gerado por Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Falha no teletransporte: dimensão {dimensionId} não está carregada.", - "iris.modded.irismoddedcommands.teleporting": "Teletransportando {value} para {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Falha no teletransporte para {dimensionId}: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teletransporte para {dimensionId} cancelado: {value} já não está online.", + "iris.modded.irismoddedcommands.teleport_refused": "O servidor recusou o teletransporte para {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Teletransportando {value} para {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} não é gerado por Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Não é possível evacuar o mundo primário; não há nenhum lugar para enviar jogadores.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuado {count} jogador( s) de {value} para {value2}.", diff --git a/core/src/main/resources/languages/ru_RU.json b/core/src/main/resources/languages/ru_RU.json index 39925b540..1d3b7bb98 100644 --- a/core/src/main/resources/languages/ru_RU.json +++ b/core/src/main/resources/languages/ru_RU.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Консоль должна называть игрока: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} не генерируется путем Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Телепорт провалился: измерение {dimensionId} не загружается.", - "iris.modded.irismoddedcommands.teleporting": "телепортация {value} то {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Не удалось телепортироваться в {dimensionId}: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Телепортация в {dimensionId} отменена: {value} больше не в сети.", + "iris.modded.irismoddedcommands.teleport_refused": "Сервер отклонил телепортацию в {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"телепортация {value} то {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} не генерируется путем Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Нельзя эвакуировать основной мир, негде отправить игроков.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "эвакуированный {count} Игрок(ы) из {value} то {value2}.", diff --git a/core/src/main/resources/languages/tr_TR.json b/core/src/main/resources/languages/tr_TR.json index a57d77d0e..ae7b3d832 100644 --- a/core/src/main/resources/languages/tr_TR.json +++ b/core/src/main/resources/languages/tr_TR.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsol bir oyuncu adı olmalıdır: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} tarafından üretilmiyor Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport başarısız oldu: Boyut {dimensionId} yüklenemez.", - "iris.modded.irismoddedcommands.teleporting": "Telporting {value} tom için {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "{dimensionId} boyutuna ışınlanma başarısız oldu: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "{dimensionId} boyutuna ışınlanma iptal edildi: {value} artık çevrimiçi değil.", + "iris.modded.irismoddedcommands.teleport_refused": "Sunucu {dimensionId} boyutuna ışınlanmayı reddetti.", + "iris.modded.irismoddedcommands.teleporting":"Telporting {value} tom için {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} tarafından üretilmiyor Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "birincil dünyayı tahliye edemez; oyuncuları göndermek için hiçbir yer yoktur.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuated {count} oyuncu(s) -den {value} tom için {value2}.", diff --git a/core/src/main/resources/languages/vi_VI.json b/core/src/main/resources/languages/vi_VI.json index bf87eeec1..cffa0d123 100644 --- a/core/src/main/resources/languages/vi_VI.json +++ b/core/src/main/resources/languages/vi_VI.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Cần phải đặt tên người chơi: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} không được tạo ra bởi Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Chuyển tiếp thất bại: chiều {dimensionId} không nạp đạn.", - "iris.modded.irismoddedcommands.teleporting": "Chuyển tiếp {value} phải {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Dịch chuyển tới {dimensionId} thất bại: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Đã hủy dịch chuyển tới {dimensionId}: {value} không còn trực tuyến.", + "iris.modded.irismoddedcommands.teleport_refused": "Máy chủ đã từ chối dịch chuyển tới {dimensionId}.", + "iris.modded.irismoddedcommands.teleporting":"Chuyển tiếp {value} phải {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} không được tạo ra bởi Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Không thể sơ tán thế giới chính; không có nơi nào để gửi cầu thủ.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Đã sơ tán{count}người chơi từ{value}phải{value2}.", diff --git a/core/src/main/resources/languages/zh_CN.json b/core/src/main/resources/languages/zh_CN.json index 11e2e78c8..3d8910502 100644 --- a/core/src/main/resources/languages/zh_CN.json +++ b/core/src/main/resources/languages/zh_CN.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制台必须给玩家命名 : /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 失败: 维度 {dimensionId} 未加载。", - "iris.modded.irismoddedcommands.teleporting": "远程传送 {value} 改为: {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "传送到 {dimensionId} 失败:{reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "已取消传送到 {dimensionId}:{value} 已不在线。", + "iris.modded.irismoddedcommands.teleport_refused": "服务器拒绝了传送到 {dimensionId}。", + "iris.modded.irismoddedcommands.teleporting":"远程传送 {value} 改为: {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} 不由 Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "无法撤离主世界; 没有地方可以发送玩家 。", "iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤离{count}玩家从{value}改为:{value2}.", diff --git a/core/src/main/resources/languages/zh_TW.json b/core/src/main/resources/languages/zh_TW.json index 3221bccb2..d0a72ae4d 100644 --- a/core/src/main/resources/languages/zh_TW.json +++ b/core/src/main/resources/languages/zh_TW.json @@ -307,7 +307,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制檯必須給玩家命名 : /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 失敗: 維度 {dimensionId} 未載入。", - "iris.modded.irismoddedcommands.teleporting": "遠端傳送 {value} 改為: {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "傳送到 {dimensionId} 失敗:{reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "已取消傳送到 {dimensionId}:{value} 已不在線上。", + "iris.modded.irismoddedcommands.teleport_refused": "伺服器拒絕了傳送到 {dimensionId}。", + "iris.modded.irismoddedcommands.teleporting":"遠端傳送 {value} 改為: {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} 不由 Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "無法撤離主世界; 沒有地方可以傳送玩家 。", "iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤離{count}玩家從{value}改為:{value2}.", diff --git a/core/src/main/resources/messages/en_US.json b/core/src/main/resources/messages/en_US.json index 5165b5e89..ee94e4f9d 100644 --- a/core/src/main/resources/messages/en_US.json +++ b/core/src/main/resources/messages/en_US.json @@ -284,7 +284,10 @@ "iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console must name a player: /iris tp ", "iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} is not generated by Iris.", "iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport failed: dimension {dimensionId} is not loaded.", - "iris.modded.irismoddedcommands.teleporting": "Teleporting {value} to {dimensionId}...", + "iris.modded.irismoddedcommands.teleport_failed_reason": "Teleport into {dimensionId} failed: {reason}", + "iris.modded.irismoddedcommands.teleport_cancelled_player_offline": "Teleport into {dimensionId} cancelled: {value} is no longer online.", + "iris.modded.irismoddedcommands.teleport_refused": "Teleport into {dimensionId} was refused by the server.", + "iris.modded.irismoddedcommands.teleporting":"Teleporting {value} to {dimensionId}...", "iris.modded.irismoddedcommands.is_not_generated_by_iris_2": "{value} is not generated by Iris.", "iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Cannot evacuate the primary world; there is nowhere to send players.", "iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuated {count} player(s) from {value} to {value2}.", diff --git a/core/src/test/java/art/arcane/iris/core/ServerTimeoutConfigurationTest.java b/core/src/test/java/art/arcane/iris/core/ServerTimeoutConfigurationTest.java new file mode 100644 index 000000000..f87687f5c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/ServerTimeoutConfigurationTest.java @@ -0,0 +1,192 @@ +package art.arcane.iris.core; + +import art.arcane.iris.spi.IrisLogging; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.MockedStatic; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; + +public class ServerTimeoutConfigurationTest { + private static final String SPIGOT_KEY = ServerTimeoutConfiguration.SPIGOT_TIMEOUT_KEY; + private static final String PAPER_KEY = ServerTimeoutConfiguration.PAPER_WATCHDOG_KEY; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void originalValuesSurviveRestartsAndRestoreIndependently() throws Exception { + Path spigot = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + Path paper = configuration("paper-global.yml", "watchdog:\n early-warning-delay: 10000\n early-warning-every: 5000\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(spigot, timeouts()); + ServerConfigurator.increasePaperWatchdog(paper, timeouts()); + ServerConfigurator.increaseKeepAliveSpigot(spigot, timeouts()); + timeouts().restore(SPIGOT_KEY); + assertEquals(60L, load(spigot).getLong(SPIGOT_KEY)); + assertEquals(180000L, load(paper).getLong(PAPER_KEY)); + timeouts().restore(PAPER_KEY); + assertEquals(10000L, load(paper).getLong(PAPER_KEY)); + assertEquals(5000L, load(paper).getLong("watchdog.early-warning-every")); + assertFalse(Files.readString(recoveryFile()).contains("spigot.yml")); + assertFalse(Files.readString(recoveryFile()).contains("paper-global.yml")); + } + } + + @Test + public void valueAtOrAboveTheMinimumIsLeftAlone() throws Exception { + String original = "settings:\n timeout-time: 600\n"; + Path file = configuration("spigot.yml", original); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + assertEquals(original, Files.readString(file)); + assertFalse(Files.exists(recoveryFile())); + } + } + + @Test + public void restoringAbsentSettingRemovesTheOverride() throws Exception { + Path file = configuration("spigot.yml", "settings:\n unrelated: retained\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + assertEquals(300L, load(file).getLong(SPIGOT_KEY)); + timeouts().restore(SPIGOT_KEY); + assertFalse(load(file).isSet(SPIGOT_KEY)); + assertEquals("retained", load(file).getString("settings.unrelated")); + } + } + + @Test + public void restorePreservesOperatorChangesAndOtherSettings() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + Files.writeString(file, "# Operator settings\nsettings:\n timeout-time: 90\n unrelated: retained\n"); + String changed = Files.readString(file); + timeouts().restore(SPIGOT_KEY); + assertEquals(changed, Files.readString(file)); + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + timeouts().restore(SPIGOT_KEY); + assertEquals(90L, load(file).getLong(SPIGOT_KEY)); + assertEquals("retained", load(file).getString("settings.unrelated")); + } + } + + @Test + public void symlinkSurvivesRaiseAndRestore() throws Exception { + Path target = configuration("shared-spigot.yml", "settings:\n timeout-time: 60\n"); + Path link = temporaryFolder.getRoot().toPath().resolve("spigot.yml"); + Files.createSymbolicLink(link, target.getFileName()); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(link, timeouts()); + assertEquals(300L, load(target).getLong(SPIGOT_KEY)); + timeouts().restore(SPIGOT_KEY); + assertTrue(Files.isSymbolicLink(link)); + assertEquals(60L, load(target).getLong(SPIGOT_KEY)); + } + } + + @Test + public void aLaterAdjustmentRecordsTheOperatorsNewOriginal() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + Files.writeString(file, "settings:\n timeout-time: 90\n"); + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + timeouts().restore(SPIGOT_KEY); + assertEquals(90L, load(file).getLong(SPIGOT_KEY)); + } + } + + @Test + public void failedRecoveryWriteLeavesServerSettingsUntouched() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + Path blocked = temporaryFolder.newFile("blocked").toPath(); + ServerTimeoutConfiguration timeouts = new ServerTimeoutConfiguration(blocked.resolve("server-timeouts.json")); + assertThrows(IOException.class, () -> timeouts.raise(file, SPIGOT_KEY, 300L)); + assertEquals(60L, load(file).getLong(SPIGOT_KEY)); + } + + @Test + public void failedServerWriteKeepsTheOriginalRecorded() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + try (MockedStatic writes = mockStatic(ServerConfigurator.class, CALLS_REAL_METHODS)) { + writes.when(() -> ServerConfigurator.writeStringAtomic(eq(file.toRealPath()), anyString())) + .thenThrow(new IOException("blocked server write")); + assertThrows(IOException.class, () -> timeouts().raise(file, SPIGOT_KEY, 300L)); + } + assertEquals(60L, load(file).getLong(SPIGOT_KEY)); + assertTrue(Files.readString(recoveryFile()).contains("\"original\": 60")); + } + + @Test + public void interruptedRestoreRetriesWithoutOverwritingLaterOperatorEdits() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + try (MockedStatic writes = mockStatic(ServerConfigurator.class, CALLS_REAL_METHODS)) { + writes.when(() -> ServerConfigurator.writeStringAtomic(eq(recoveryFile()), anyString())) + .thenThrow(new IOException("interrupted recovery write")); + assertThrows(IOException.class, () -> timeouts().restore(SPIGOT_KEY)); + } + assertTrue(Files.readString(recoveryFile()).contains("spigot.yml")); + Files.writeString(file, "settings:\n timeout-time: 120\n"); + timeouts().restore(SPIGOT_KEY); + assertEquals(120L, load(file).getLong(SPIGOT_KEY)); + assertFalse(Files.readString(recoveryFile()).contains("spigot.yml")); + } + } + + @Test + public void recordForADeletedFileIsDropped() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + try (MockedStatic logging = mockStatic(IrisLogging.class)) { + ServerConfigurator.increaseKeepAliveSpigot(file, timeouts()); + Files.delete(file); + timeouts().restore(SPIGOT_KEY); + assertFalse(Files.readString(recoveryFile()).contains("spigot.yml")); + } + } + + @Test + public void malformedRecoveryDataPreventsNewConfigurationWrites() throws Exception { + Path file = configuration("spigot.yml", "settings:\n timeout-time: 60\n"); + Files.writeString(recoveryFile(), "{invalid"); + assertThrows(IOException.class, () -> timeouts().raise(file, SPIGOT_KEY, 300L)); + assertEquals(60L, load(file).getLong(SPIGOT_KEY)); + assertEquals("{invalid", Files.readString(recoveryFile())); + } + + private Path configuration(String name, String content) throws IOException { + Path file = temporaryFolder.newFile(name).toPath(); + Files.writeString(file, content); + return file; + } + + private ServerTimeoutConfiguration timeouts() { + return new ServerTimeoutConfiguration(recoveryFile()); + } + + private Path recoveryFile() { + return temporaryFolder.getRoot().toPath().resolve("server-timeouts.json"); + } + + private static YamlConfiguration load(Path file) throws Exception { + YamlConfiguration configuration = new YamlConfiguration(); + configuration.load(file.toFile()); + return configuration; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalServiceTest.java b/core/src/test/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalServiceTest.java index c474c5d7a..b566e3a3a 100644 --- a/core/src/test/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalServiceTest.java +++ b/core/src/test/java/art/arcane/iris/core/lifecycle/IrisWorldRemovalServiceTest.java @@ -67,12 +67,26 @@ public class IrisWorldRemovalServiceTest { assertTrue(result.succeeded()); assertTrue(result.registryChanged()); assertEquals( - List.of("resolve", "begin", "evacuate", "unload", "close", "unregister", "unregisterRegistry", "end"), + List.of("resolve", "evacuate", "begin", "unload", "close", "unregister", "unregisterRegistry", "end"), backend.operations ); assertTrue(coordinator.isIdle()); } + @Test + public void mantleBypassMaintenanceStartsOnlyAfterPlayersLeave() throws Exception { + LifecycleOperationCoordinator coordinator = new LifecycleOperationCoordinator(); + FakeBackend backend = new FakeBackend(target("evacuation-failed")); + backend.evacuation = CompletableFuture.failedFuture(new IllegalStateException("no destination world")); + IrisWorldRemovalService service = new IrisWorldRemovalService(coordinator, backend); + + IrisWorldRemovalService.RemovalResult result = service.remove("evacuation-failed", true).join(); + + assertEquals(IrisWorldRemovalService.RemovalStatus.TELEPORT_FAILED, result.status()); + assertEquals(List.of("resolve", "evacuate"), backend.operations); + assertTrue(coordinator.isIdle()); + } + @Test public void configurationFailureStopsBeforeDeletionAndRetainsCause() throws Exception { LifecycleOperationCoordinator coordinator = new LifecycleOperationCoordinator(); diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorCloseSequenceTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorCloseSequenceTest.java index 14d3fa2b8..571158c13 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorCloseSequenceTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorCloseSequenceTest.java @@ -22,12 +22,37 @@ public class StudioOpenCoordinatorCloseSequenceTest { StudioOpenCoordinator.sequenceStudioClose( () -> phase(phases, "evacuate"), + () -> phases.add("maintenance"), () -> phase(phases, "unload"), () -> phase(phases, "close-generator"), () -> phase(phases, "delete-folders") ).join(); - assertEquals(List.of("evacuate", "unload", "close-generator", "delete-folders"), phases); + assertEquals(List.of("evacuate", "maintenance", "unload", "close-generator", "delete-folders"), phases); + } + + @Test + public void evacuationFailureNeverEntersMaintenance() { + ArrayList phases = new ArrayList<>(); + IllegalStateException failure = new IllegalStateException("evacuation failed"); + + try { + StudioOpenCoordinator.sequenceStudioClose( + () -> { + phases.add("evacuate"); + return CompletableFuture.failedFuture(failure); + }, + () -> phases.add("maintenance"), + () -> phase(phases, "unload"), + () -> phase(phases, "close-generator"), + () -> phase(phases, "delete-folders") + ).join(); + fail("Expected evacuation failure"); + } catch (CompletionException exception) { + assertSame(failure, exception.getCause()); + } + + assertEquals(List.of("evacuate"), phases); } @Test @@ -38,6 +63,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { try { StudioOpenCoordinator.sequenceStudioClose( () -> phase(phases, "evacuate"), + () -> phases.add("maintenance"), () -> { phases.add("unload"); return CompletableFuture.failedFuture(failure); @@ -50,7 +76,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { assertSame(failure, exception.getCause()); } - assertEquals(List.of("evacuate", "unload"), phases); + assertEquals(List.of("evacuate", "maintenance", "unload"), phases); } @Test @@ -61,6 +87,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { try { StudioOpenCoordinator.sequenceStudioClose( () -> phase(phases, "evacuate"), + () -> phases.add("maintenance"), () -> phase(phases, "unload"), () -> { phases.add("close-generator"); @@ -73,7 +100,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { assertSame(failure, exception.getCause()); } - assertEquals(List.of("evacuate", "unload", "close-generator"), phases); + assertEquals(List.of("evacuate", "maintenance", "unload", "close-generator"), phases); } @Test @@ -84,6 +111,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { CompletableFuture close = StudioOpenCoordinator.sequenceStudioClose( () -> phase(phases, "evacuate"), + () -> phases.add("maintenance"), () -> { phases.add("unload"); return unload; @@ -100,7 +128,7 @@ public class StudioOpenCoordinatorCloseSequenceTest { } catch (CompletionException exception) { assertEquals("Studio close stopped after its terminal timeout.", exception.getCause().getMessage()); } - assertEquals(List.of("evacuate", "unload"), phases); + assertEquals(List.of("evacuate", "maintenance", "unload"), phases); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/IrisWorldManagerNativePoiTest.java b/core/src/test/java/art/arcane/iris/engine/IrisWorldManagerNativePoiTest.java new file mode 100644 index 000000000..5f8d3e4be --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/IrisWorldManagerNativePoiTest.java @@ -0,0 +1,52 @@ +package art.arcane.iris.engine; + +import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.core.nms.INMSBinding; +import art.arcane.iris.engine.framework.Engine; +import org.bukkit.Chunk; +import org.junit.Test; +import org.mockito.MockedStatic; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class IrisWorldManagerNativePoiTest { + @Test + public void chunkLoadReconcilesPoisWithoutAnOptionalCleanupExecutor() { + IrisWorldManager manager = mock(IrisWorldManager.class, CALLS_REAL_METHODS); + Engine engine = mock(Engine.class); + Chunk chunk = mock(Chunk.class); + INMSBinding binding = mock(INMSBinding.class); + when(manager.getEngine()).thenReturn(engine); + + try (MockedStatic nms = mockStatic(INMS.class)) { + nms.when(INMS::get).thenReturn(binding); + manager.onChunkLoad(chunk, false); + } + + verify(binding).reconcileNativeStructurePois(chunk); + } + + @Test + public void chunkLoadPropagatesPoiFailuresToTheRuntimeEventReporter() { + IrisWorldManager manager = mock(IrisWorldManager.class, CALLS_REAL_METHODS); + Engine engine = mock(Engine.class); + Chunk chunk = mock(Chunk.class); + INMSBinding binding = mock(INMSBinding.class); + IllegalStateException failure = new IllegalStateException("Native POI storage failure"); + when(manager.getEngine()).thenReturn(engine); + doThrow(failure).when(binding).reconcileNativeStructurePois(chunk); + + try (MockedStatic nms = mockStatic(INMS.class)) { + nms.when(INMS::get).thenReturn(binding); + assertSame(failure, assertThrows(IllegalStateException.class, + () -> manager.onChunkLoad(chunk, true))); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitBiomeTest.java b/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitBiomeTest.java new file mode 100644 index 000000000..3e637096e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/platform/bukkit/BukkitBiomeTest.java @@ -0,0 +1,154 @@ +package art.arcane.iris.platform.bukkit; + +import art.arcane.iris.spi.PlatformBiome; +import com.github.benmanes.caffeine.cache.Cache; +import org.bukkit.NamespacedKey; +import org.junit.Before; +import org.junit.Test; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class BukkitBiomeTest { + private Class biomeType; + private Method wrap; + + @Before + public void loadAdapterWithoutServerRegistryInitialization() throws Exception { + ClassLoader loader = new BiomeClassLoader(); + biomeType = loader.loadClass("org.bukkit.block.Biome"); + wrap = loader.loadClass(BukkitBiome.class.getName()).getMethod("of", biomeType); + } + + @Test + public void cachedHandlesKeepCanonicalIdentityWithoutReadingTheKeyAgain() throws Exception { + AtomicInteger keyReads = new AtomicInteger(); + Object biome = biome("iris", "riverbank", keyReads); + + PlatformBiome wrapped = wrap(biome); + assertEquals("iris:riverbank", wrapped.key()); + assertEquals("iris", wrapped.namespace()); + assertSame(biome, wrapped.nativeHandle()); + assertSame(wrapped, wrap(biome)); + assertSame(wrapped, wrap(biome)); + assertEquals(1, keyReads.get()); + } + + @Test + public void replacementRegistryHandleCannotReturnThePreviousNativeBiome() throws Exception { + Object previous = biome("iris", "registry_replacement", new AtomicInteger()); + Object replacement = biome("iris", "registry_replacement", new AtomicInteger()); + + PlatformBiome oldHandle = wrap(previous); + PlatformBiome newHandle = wrap(replacement); + + assertNotSame(oldHandle, newHandle); + assertEquals(oldHandle.key(), newHandle.key()); + assertSame(previous, oldHandle.nativeHandle()); + assertSame(replacement, newHandle.nativeHandle()); + assertSame(newHandle, wrap(replacement)); + } + + @Test + public void customAndVanillaNamespacesRemainDistinct() throws Exception { + PlatformBiome vanilla = wrap(biome("minecraft", "plains", new AtomicInteger())); + PlatformBiome custom = wrap(biome("iris", "plains", new AtomicInteger())); + + assertEquals("minecraft:plains", vanilla.key()); + assertEquals("minecraft", vanilla.namespace()); + assertEquals("iris:plains", custom.key()); + assertNotSame(vanilla, custom); + } + + @Test + public void cacheEvictionPreservesBiomeKeysAndNativeHandles() throws Exception { + Object retained = biome("iris", "retained", new AtomicInteger()); + PlatformBiome original = wrap(retained); + for (int index = 0; index < 8_192; index++) { + wrap(biome("iris", "eviction_" + index, new AtomicInteger())); + } + Field field = wrap.getDeclaringClass().getDeclaredField("CACHE"); + field.setAccessible(true); + Cache cache = (Cache) field.get(null); + cache.cleanUp(); + + assertTrue(cache.estimatedSize() <= 4_096); + PlatformBiome restored = wrap(retained); + assertEquals(original.key(), restored.key()); + assertEquals(original.namespace(), restored.namespace()); + assertSame(retained, restored.nativeHandle()); + } + + private PlatformBiome wrap(Object biome) throws Exception { + return (PlatformBiome) wrap.invoke(null, biome); + } + + private Object biome(String namespace, String name, AtomicInteger keyReads) { + NamespacedKey key = new NamespacedKey(namespace, name); + return Proxy.newProxyInstance(biomeType.getClassLoader(), new Class[]{biomeType}, (proxy, method, arguments) -> switch (method.getName()) { + case "getKey" -> { + keyReads.incrementAndGet(); + yield key; + } + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == arguments[0]; + case "toString" -> key.toString(); + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + private static final class BiomeClassLoader extends ClassLoader { + private BiomeClassLoader() { + super(BukkitBiomeTest.class.getClassLoader()); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!name.equals("org.bukkit.block.Biome") && !name.equals(BukkitBiome.class.getName())) { + return super.loadClass(name, resolve); + } + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + try (InputStream source = getParent().getResourceAsStream(name.replace('.', '/') + ".class")) { + if (source == null) { + throw new ClassNotFoundException(name); + } + byte[] bytecode = source.readAllBytes(); + if (name.equals("org.bukkit.block.Biome")) { + ClassWriter writer = new ClassWriter(0); + new ClassReader(bytecode).accept(new ClassVisitor(Opcodes.ASM9, writer) { + @Override + public MethodVisitor visitMethod(int access, String method, String descriptor, String signature, String[] exceptions) { + return method.equals("") ? null : super.visitMethod(access, method, descriptor, signature, exceptions); + } + }, 0); + bytecode = writer.toByteArray(); + } + loaded = defineClass(name, bytecode, 0, bytecode.length); + } catch (IOException exception) { + throw new ClassNotFoundException(name, exception); + } + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + } + } +}