mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-01 18:24:06 +00:00
Merge upstream port lane d
NativeStructureWorldgenAccess keeps both sides: writes are still recorded for the stale deferred-record check, and they go through the POI reconciler when one is bound.
This commit is contained in:
commit
4b1d85177f
69 files changed
+2413
-255
No files matched your search
+5
@@ -1153,6 +1153,11 @@ public class NMSBinding implements INMSBinding {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void reconcileNativeStructurePois(Chunk chunk) {
|
||||||
|
NativeStructurePoiUpdates.reconcile((LevelChunk) ((CraftChunk) chunk).getHandle(ChunkStatus.FULL));
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean clearChunkBlocks(Chunk bukkitChunk) {
|
public boolean clearChunkBlocks(Chunk bukkitChunk) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
+142
@@ -0,0 +1,142 @@
|
|||||||
|
package art.arcane.iris.core.nms.v26_2_R1;
|
||||||
|
|
||||||
|
import ca.spottedleaf.moonrise.common.util.TickThread;
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.core.Holder;
|
||||||
|
import net.minecraft.core.SectionPos;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiSection;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiType;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
|
||||||
|
import net.minecraft.world.level.WorldGenLevel;
|
||||||
|
import net.minecraft.world.level.block.Block;
|
||||||
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
|
import net.minecraft.world.level.chunk.ChunkAccess;
|
||||||
|
import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
||||||
|
import net.minecraft.world.level.chunk.LevelChunk;
|
||||||
|
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||||
|
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
final class NativeStructurePoiUpdates {
|
||||||
|
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
|
||||||
|
|
||||||
|
private final int skipPoiFlag;
|
||||||
|
|
||||||
|
NativeStructurePoiUpdates(int skipPoiFlag) {
|
||||||
|
this.skipPoiFlag = skipPoiFlag;
|
||||||
|
}
|
||||||
|
|
||||||
|
static NativeStructurePoiUpdates create() {
|
||||||
|
try {
|
||||||
|
return new NativeStructurePoiUpdates(Block.class.getField("UPDATE_SKIP_POI").getInt(null));
|
||||||
|
} catch (NoSuchFieldException e) {
|
||||||
|
return null;
|
||||||
|
} catch (IllegalAccessException e) {
|
||||||
|
throw new ExceptionInInitializerError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean setBlock(WorldGenLevel world, BlockPos position, BlockState state, int flags, int limit) {
|
||||||
|
if ((flags & skipPoiFlag) != 0) {
|
||||||
|
return world.setBlock(position, state, flags, limit);
|
||||||
|
}
|
||||||
|
ChunkAccess chunk = world.getChunk(position);
|
||||||
|
if (!(chunk instanceof ProtoChunk)) {
|
||||||
|
return world.setBlock(position, state, flags, limit);
|
||||||
|
}
|
||||||
|
if (!(chunk instanceof ImposterProtoChunk)
|
||||||
|
&& !PoiTypes.forState(chunk.getBlockState(position)).equals(PoiTypes.forState(state))) {
|
||||||
|
markSection(chunk, chunk.getSectionIndex(position.getY()));
|
||||||
|
}
|
||||||
|
return world.setBlock(position, state, flags | skipPoiFlag, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void reconcile(LevelChunk chunk) {
|
||||||
|
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||||
|
if (sections == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
validateSections(chunk, sections);
|
||||||
|
ServerLevel world = (ServerLevel) chunk.getLevel();
|
||||||
|
TickThread.ensureTickThread(world, chunk.getPos(), "Native structure POIs require the chunk owning thread");
|
||||||
|
PoiManager manager = world.getPoiManager();
|
||||||
|
for (int word = 0; word < sections.length; word++) {
|
||||||
|
long remaining = sections[word];
|
||||||
|
while (remaining != 0) {
|
||||||
|
int index = (word << 6) + Long.numberOfTrailingZeros(remaining);
|
||||||
|
reconcileSection(chunk, manager, index);
|
||||||
|
remaining &= remaining - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chunk.persistentDataContainer.remove(DIRTY_SECTIONS);
|
||||||
|
chunk.markUnsaved();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void markSection(ChunkAccess chunk, int index) {
|
||||||
|
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||||
|
int word = index >>> 6;
|
||||||
|
long bit = 1L << (index & 63);
|
||||||
|
if (sections == null) {
|
||||||
|
sections = new long[word + 1];
|
||||||
|
} else {
|
||||||
|
validateSections(chunk, sections);
|
||||||
|
if (word < sections.length && (sections[word] & bit) != 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (word >= sections.length) {
|
||||||
|
sections = Arrays.copyOf(sections, word + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sections[word] |= bit;
|
||||||
|
chunk.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, sections);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void validateSections(ChunkAccess chunk, long[] sections) {
|
||||||
|
int count = chunk.getSectionsCount();
|
||||||
|
int words = (count + 63) >>> 6;
|
||||||
|
if (sections.length > words
|
||||||
|
|| sections.length == words && (count & 63) != 0
|
||||||
|
&& (sections[words - 1] >>> (count & 63)) != 0) {
|
||||||
|
throw new IllegalArgumentException("Native POI repair sections exceed chunk height at " + chunk.getPos());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reconcileSection(LevelChunk chunk, PoiManager manager, int index) {
|
||||||
|
SectionPos sectionPosition = SectionPos.of(chunk.getPos(), chunk.getSectionYFromSectionIndex(index));
|
||||||
|
Optional<PoiSection> existing = manager.getOrLoad(sectionPosition.asLong());
|
||||||
|
if (existing.isPresent()) {
|
||||||
|
for (PoiRecord record : existing.get().getRecords(type -> true, PoiManager.Occupancy.ANY).toList()) {
|
||||||
|
if (!PoiTypes.forState(chunk.getBlockState(record.getPos())).equals(Optional.of(record.getPoiType()))) {
|
||||||
|
manager.remove(record.getPos());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LevelChunkSection section = chunk.getSection(index);
|
||||||
|
if (!section.maybeHas(PoiTypes::hasPoi)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
|
||||||
|
for (int y = 0; y < 16; y++) {
|
||||||
|
for (int z = 0; z < 16; z++) {
|
||||||
|
for (int x = 0; x < 16; x++) {
|
||||||
|
Optional<Holder<PoiType>> type = PoiTypes.forState(section.getBlockState(x, y, z));
|
||||||
|
if (type.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
position.set(sectionPosition.minBlockX() + x, sectionPosition.minBlockY() + y,
|
||||||
|
sectionPosition.minBlockZ() + z);
|
||||||
|
if (!manager.getType(position).equals(type)) {
|
||||||
|
manager.add(position.immutable(), type.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-3
@@ -12,6 +12,7 @@ import net.minecraft.core.RegistryAccess;
|
|||||||
import net.minecraft.core.particles.ParticleOptions;
|
import net.minecraft.core.particles.ParticleOptions;
|
||||||
import net.minecraft.server.MinecraftServer;
|
import net.minecraft.server.MinecraftServer;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.server.level.WorldGenRegion;
|
||||||
import net.minecraft.sounds.SoundEvent;
|
import net.minecraft.sounds.SoundEvent;
|
||||||
import net.minecraft.sounds.SoundSource;
|
import net.minecraft.sounds.SoundSource;
|
||||||
import net.minecraft.util.Mth;
|
import net.minecraft.util.Mth;
|
||||||
@@ -60,6 +61,7 @@ import java.util.function.Supplier;
|
|||||||
|
|
||||||
final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||||
private static final int WRITE_RADIUS = 1;
|
private static final int WRITE_RADIUS = 1;
|
||||||
|
private static final NativeStructurePoiUpdates POI_UPDATES = NativeStructurePoiUpdates.create();
|
||||||
|
|
||||||
private final WorldGenLevel delegate;
|
private final WorldGenLevel delegate;
|
||||||
private final ChunkPos generationCenter;
|
private final ChunkPos generationCenter;
|
||||||
@@ -426,23 +428,45 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
|
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
|
@Override
|
||||||
public boolean removeBlock(BlockPos position, boolean move) {
|
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
|
@Override
|
||||||
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
|
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() {
|
WrittenBlocks writtenBlocks() {
|
||||||
return writtenBlocks;
|
return writtenBlocks;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean reconcilesPoiThroughSetBlock() {
|
||||||
|
return POI_UPDATES != null && delegate instanceof WorldGenRegion;
|
||||||
|
}
|
||||||
|
|
||||||
private boolean recordWrite(BlockPos position, boolean written) {
|
private boolean recordWrite(BlockPos position, boolean written) {
|
||||||
if (written) {
|
if (written) {
|
||||||
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
|
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
|
||||||
|
|||||||
+250
@@ -0,0 +1,250 @@
|
|||||||
|
package art.arcane.iris.core.nms.v26_2_R1;
|
||||||
|
|
||||||
|
import ca.spottedleaf.moonrise.common.util.TickThread;
|
||||||
|
import com.mojang.serialization.Codec;
|
||||||
|
import net.minecraft.SharedConstants;
|
||||||
|
import net.minecraft.core.BlockPos;
|
||||||
|
import net.minecraft.core.Holder;
|
||||||
|
import net.minecraft.core.IdMapper;
|
||||||
|
import net.minecraft.core.SectionPos;
|
||||||
|
import net.minecraft.server.Bootstrap;
|
||||||
|
import net.minecraft.server.level.ServerLevel;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiSection;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiType;
|
||||||
|
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
|
||||||
|
import net.minecraft.world.level.ChunkPos;
|
||||||
|
import net.minecraft.world.level.LevelHeightAccessor;
|
||||||
|
import net.minecraft.world.level.WorldGenLevel;
|
||||||
|
import net.minecraft.world.level.biome.Biome;
|
||||||
|
import net.minecraft.world.level.block.Block;
|
||||||
|
import net.minecraft.world.level.block.Blocks;
|
||||||
|
import net.minecraft.world.level.block.state.BlockState;
|
||||||
|
import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
||||||
|
import net.minecraft.world.level.chunk.LevelChunk;
|
||||||
|
import net.minecraft.world.level.chunk.PalettedContainer;
|
||||||
|
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||||
|
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||||
|
import net.minecraft.world.level.chunk.Strategy;
|
||||||
|
import net.minecraft.world.level.chunk.UpgradeData;
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
|
import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry;
|
||||||
|
import org.bukkit.craftbukkit.persistence.DirtyCraftPersistentDataContainer;
|
||||||
|
import org.bukkit.persistence.PersistentDataType;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.FutureTask;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
import static org.junit.Assert.assertThrows;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyInt;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
public class NativeStructurePoiUpdatesTest {
|
||||||
|
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void bootstrapMinecraftRegistries() {
|
||||||
|
SharedConstants.tryDetectVersion();
|
||||||
|
Bootstrap.bootStrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void generationRecordsIntentBeforeSuppressingNativePoiCallbacks() {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
BlockPos position = new BlockPos(-31, 5, 49);
|
||||||
|
doAnswer(call -> {
|
||||||
|
assertNotNull(fixture.proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY));
|
||||||
|
assertEquals(Block.UPDATE_CLIENTS | 4096, (int) call.getArgument(2));
|
||||||
|
fixture.proto.setBlockState(position, call.getArgument(1), 0);
|
||||||
|
return true;
|
||||||
|
}).when(fixture.world).setBlock(any(), any(), anyInt(), anyInt());
|
||||||
|
|
||||||
|
assertTrue(fixture.updates.setBlock(fixture.world, position,
|
||||||
|
Blocks.COMPOSTER.defaultBlockState(), Block.UPDATE_CLIENTS, 17));
|
||||||
|
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void denseWritesStoreOneSectionBitAndSurvivePersistentDataRoundTrip() throws Exception {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
for (int z = 0; z < 16; z++) {
|
||||||
|
for (int x = 0; x < 16; x++) {
|
||||||
|
fixture.write(new BlockPos(-32 + x, 5, 48 + z), Blocks.COMPOSTER.defaultBlockState());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||||
|
DirtyCraftPersistentDataContainer restored = new DirtyCraftPersistentDataContainer(new CraftPersistentDataTypeRegistry());
|
||||||
|
restored.putAll(fixture.proto.persistentDataContainer.toTagCompound());
|
||||||
|
fixture.loaded.persistentDataContainer = restored;
|
||||||
|
|
||||||
|
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||||
|
|
||||||
|
assertEquals(256L, fixture.records().getRecords(type -> true, PoiManager.Occupancy.ANY).count());
|
||||||
|
assertFalse(restored.has(DIRTY_SECTIONS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void validSectionsReconcileFinalStatesAndKeepMatchingClaimedTickets() throws Exception {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
BlockPos retained = new BlockPos(-31, 5, 49);
|
||||||
|
BlockPos replaced = new BlockPos(-30, 5, 49);
|
||||||
|
BlockPos removed = new BlockPos(-29, 5, 49);
|
||||||
|
Holder<PoiType> farmer = PoiTypes.forState(Blocks.COMPOSTER.defaultBlockState()).orElseThrow();
|
||||||
|
PoiSection existing = new PoiSection.Packed(true, List.of(
|
||||||
|
new PoiRecord.Packed(retained, farmer, 0),
|
||||||
|
new PoiRecord.Packed(replaced, farmer, 1),
|
||||||
|
new PoiRecord.Packed(removed, farmer, 1))).unpack(() -> {});
|
||||||
|
fixture.pois.put(SectionPos.of(retained).asLong(), existing);
|
||||||
|
PoiRecord retainedRecord = existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
|
||||||
|
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow();
|
||||||
|
for (BlockPos position : List.of(retained, replaced, removed)) {
|
||||||
|
fixture.proto.setBlockState(position, Blocks.COMPOSTER.defaultBlockState(), 0);
|
||||||
|
}
|
||||||
|
fixture.write(replaced, Blocks.BARREL.defaultBlockState());
|
||||||
|
fixture.write(removed, Blocks.AIR.defaultBlockState());
|
||||||
|
|
||||||
|
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||||
|
|
||||||
|
assertEquals(PoiTypes.forState(Blocks.BARREL.defaultBlockState()), existing.getType(replaced));
|
||||||
|
assertTrue(existing.getType(removed).isEmpty());
|
||||||
|
assertSame(retainedRecord, existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
|
||||||
|
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow());
|
||||||
|
assertEquals(0, existing.getFreeTickets(retained));
|
||||||
|
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||||
|
assertEquals(0, existing.getFreeTickets(retained));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void failedReconciliationRetainsIntentForRetry() throws Exception {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
fixture.write(new BlockPos(-31, 5, 49), Blocks.COMPOSTER.defaultBlockState());
|
||||||
|
IllegalStateException failure = new IllegalStateException("POI storage failure");
|
||||||
|
doThrow(failure).when(fixture.manager).add(any(), any());
|
||||||
|
|
||||||
|
onOwner(() -> assertSame(failure, assertThrows(IllegalStateException.class,
|
||||||
|
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded))));
|
||||||
|
|
||||||
|
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||||
|
fixture.allowPoiAdds();
|
||||||
|
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||||
|
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void explicitPoiSuppressionAndReadOnlyFullChunksDoNotCreateIntent() {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
BlockPos position = new BlockPos(-31, 5, 49);
|
||||||
|
fixture.updates.setBlock(fixture.world, position, Blocks.COMPOSTER.defaultBlockState(),
|
||||||
|
4096, 17);
|
||||||
|
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||||
|
ImposterProtoChunk full = mock(ImposterProtoChunk.class);
|
||||||
|
when(fixture.world.getChunk(any(BlockPos.class))).thenReturn(full);
|
||||||
|
fixture.updates.setBlock(fixture.world, position, Blocks.BARREL.defaultBlockState(), 2, 17);
|
||||||
|
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invalidSectionBitsRetainTheStoredRecord() throws Exception {
|
||||||
|
Fixture fixture = new Fixture();
|
||||||
|
fixture.proto.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, new long[]{1L << 24});
|
||||||
|
onOwner(() -> assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded)));
|
||||||
|
assertArrayEquals(new long[]{1L << 24}, fixture.marker());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void onOwner(Runnable action) throws Exception {
|
||||||
|
FutureTask<Void> task = new FutureTask<>(action, null);
|
||||||
|
new TickThread(task, "Native POI test").start();
|
||||||
|
task.get(5L, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PalettedContainerFactory containerFactory() {
|
||||||
|
Strategy<BlockState> blocks = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY);
|
||||||
|
BlockState air = Blocks.AIR.defaultBlockState();
|
||||||
|
IdMapper<Holder<Biome>> biomeIds = new IdMapper<>();
|
||||||
|
Holder<Biome> biome = Holder.direct((Biome) null);
|
||||||
|
biomeIds.add(biome);
|
||||||
|
Strategy<Holder<Biome>> biomes = Strategy.createForBiomes(biomeIds);
|
||||||
|
Codec<Holder<Biome>> biomeCodec = Codec.STRING.xmap(name -> biome, holder -> "iris-test-biome");
|
||||||
|
return new PalettedContainerFactory(blocks, air, PalettedContainer.codecRW(BlockState.CODEC, blocks, air),
|
||||||
|
biomes, biome, PalettedContainer.codecRO(biomeCodec, biomes, biome),
|
||||||
|
PalettedContainer.codecRW(biomeCodec, biomes, biome));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Fixture {
|
||||||
|
private final NativeStructurePoiUpdates updates = new NativeStructurePoiUpdates(4096);
|
||||||
|
private final ProtoChunk proto = new ProtoChunk(new ChunkPos(-2, 3), UpgradeData.EMPTY,
|
||||||
|
LevelHeightAccessor.create(-64, 384), containerFactory(), null);
|
||||||
|
private final LevelChunk loaded = mock(LevelChunk.class);
|
||||||
|
private final WorldGenLevel world = mock(WorldGenLevel.class);
|
||||||
|
private final PoiManager manager = mock(PoiManager.class);
|
||||||
|
private final Map<Long, PoiSection> pois = new HashMap<>();
|
||||||
|
|
||||||
|
private Fixture() {
|
||||||
|
ServerLevel level = mock(ServerLevel.class);
|
||||||
|
when(level.getPoiManager()).thenReturn(manager);
|
||||||
|
loaded.persistentDataContainer = proto.persistentDataContainer;
|
||||||
|
when(loaded.getLevel()).thenReturn(level);
|
||||||
|
when(loaded.getPos()).thenReturn(proto.getPos());
|
||||||
|
when(loaded.getSectionsCount()).thenReturn(proto.getSectionsCount());
|
||||||
|
when(loaded.getSectionYFromSectionIndex(anyInt())).thenAnswer(call -> proto.getSectionYFromSectionIndex(call.getArgument(0)));
|
||||||
|
when(loaded.getSection(anyInt())).thenAnswer(call -> proto.getSection(call.getArgument(0)));
|
||||||
|
when(loaded.getBlockState(any())).thenAnswer(call -> proto.getBlockState(call.getArgument(0)));
|
||||||
|
when(world.getChunk(any(BlockPos.class))).thenReturn(proto);
|
||||||
|
when(world.setBlock(any(), any(), anyInt(), anyInt())).thenAnswer(call -> {
|
||||||
|
proto.setBlockState(call.getArgument(0), call.getArgument(1), call.getArgument(2));
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
when(manager.getOrLoad(anyLong())).thenAnswer(call -> Optional.ofNullable(pois.get((long) call.getArgument(0))));
|
||||||
|
when(manager.getType(any())).thenAnswer(call -> {
|
||||||
|
BlockPos position = call.getArgument(0);
|
||||||
|
PoiSection section = pois.get(SectionPos.of(position).asLong());
|
||||||
|
return section == null ? Optional.empty() : section.getType(position);
|
||||||
|
});
|
||||||
|
doAnswer(call -> {
|
||||||
|
BlockPos position = call.getArgument(0);
|
||||||
|
pois.get(SectionPos.of(position).asLong()).remove(position);
|
||||||
|
return null;
|
||||||
|
}).when(manager).remove(any());
|
||||||
|
allowPoiAdds();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void allowPoiAdds() {
|
||||||
|
doAnswer(call -> {
|
||||||
|
BlockPos position = call.getArgument(0);
|
||||||
|
return pois.computeIfAbsent(SectionPos.of(position).asLong(), ignored -> new PoiSection(() -> {}))
|
||||||
|
.add(position, call.getArgument(1));
|
||||||
|
}).when(manager).add(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void write(BlockPos position, BlockState state) {
|
||||||
|
updates.setBlock(world, position, state, Block.UPDATE_CLIENTS, Block.UPDATE_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long[] marker() {
|
||||||
|
return proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PoiSection records() {
|
||||||
|
return pois.get(SectionPos.of(new BlockPos(-31, 5, 49)).asLong());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ import art.arcane.iris.core.link.IrisPapiListener;
|
|||||||
import art.arcane.iris.core.link.IrisPapiState;
|
import art.arcane.iris.core.link.IrisPapiState;
|
||||||
import art.arcane.iris.core.localization.IrisLanguage;
|
import art.arcane.iris.core.localization.IrisLanguage;
|
||||||
import art.arcane.iris.core.link.MultiverseCoreLink;
|
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.nms.INMS;
|
||||||
import art.arcane.iris.core.gui.BukkitGuiHost;
|
import art.arcane.iris.core.gui.BukkitGuiHost;
|
||||||
import art.arcane.iris.core.gui.PregeneratorJob;
|
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 PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this);
|
||||||
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
|
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
|
||||||
private volatile SettingsHotloadWatch settingsHotloadWatch;
|
private volatile SettingsHotloadWatch settingsHotloadWatch;
|
||||||
private volatile Thread serverLifecycleThread;
|
|
||||||
|
|
||||||
public static VolmitSender getSender() {
|
public static VolmitSender getSender() {
|
||||||
VolmitSender current = sender;
|
VolmitSender current = sender;
|
||||||
@@ -540,6 +540,17 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
this::getIrisVersion,
|
this::getIrisVersion,
|
||||||
this::getMCVersion));
|
this::getMCVersion));
|
||||||
SlimJar.load();
|
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) {
|
private static void bridgeLog(LogLevel level, String message) {
|
||||||
@@ -746,7 +757,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
|
|
||||||
public void addShutdownHook() {
|
public void addShutdownHook() {
|
||||||
removeShutdownHook();
|
removeShutdownHook();
|
||||||
serverLifecycleThread = Thread.currentThread();
|
|
||||||
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
|
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
|
||||||
try {
|
try {
|
||||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||||
@@ -877,6 +887,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void onDisable() {
|
public void onDisable() {
|
||||||
|
pendingWorldReplacements.awaitStagingForShutdown();
|
||||||
teardownPapi();
|
teardownPapi();
|
||||||
boolean serverStopping = IrisToolbelt.isServerStopping();
|
boolean serverStopping = IrisToolbelt.isServerStopping();
|
||||||
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
|
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
|
||||||
@@ -1012,7 +1023,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
if (generator == null) {
|
if (generator == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
IrisToolbelt.beginWorldMaintenance(world, reason, true);
|
IrisToolbelt.beginWorldMaintenance(world, reason);
|
||||||
if (!deferredShutdownGenerators.contains(generator)) {
|
if (!deferredShutdownGenerators.contains(generator)) {
|
||||||
deferredShutdownGenerators.add(generator);
|
deferredShutdownGenerators.add(generator);
|
||||||
}
|
}
|
||||||
@@ -1024,51 +1035,31 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
if (!postStopFinisherStarted.compareAndSet(false, true)) {
|
if (!postStopFinisherStarted.compareAndSet(false, true)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Thread activeServerThread = serverLifecycleThread;
|
Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"),
|
||||||
if (activeServerThread == null) {
|
"Iris-PostStop-Finisher");
|
||||||
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");
|
|
||||||
finisher.setDaemon(false);
|
finisher.setDaemon(false);
|
||||||
finisher.start();
|
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() {
|
private void runShutdownHook() {
|
||||||
if (startupBoundaryRestart.get()) {
|
if (startupBoundaryRestart.get()) {
|
||||||
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
|
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
finishRuntimeAfterServerShutdown("shutdown-hook");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishRuntimeAfterServerShutdown(String reason) {
|
||||||
if (!awaitServerShutdownBoundary()) {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
finishDeferredRuntimeTeardown("shutdown-hook", 30L);
|
finishDeferredRuntimeTeardown(reason, 30L);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean awaitServerShutdownBoundary() {
|
private boolean awaitServerShutdownBoundary() {
|
||||||
if (!INMS.isBound()) {
|
if (!INMS.isBound()) {
|
||||||
return true;
|
return false;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return INMS.get().awaitServerShutdownBoundary(
|
return INMS.get().awaitServerShutdownBoundary(
|
||||||
@@ -1281,12 +1272,15 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
|||||||
public int getIrisVersion() {
|
public int getIrisVersion() {
|
||||||
String input = getDescription().getVersion();
|
String input = getDescription().getVersion();
|
||||||
int hyphenIndex = input.indexOf('-');
|
int hyphenIndex = input.indexOf('-');
|
||||||
if (hyphenIndex != -1) {
|
String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex);
|
||||||
String result = input.substring(0, hyphenIndex);
|
if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) {
|
||||||
result = result.replaceAll("\\.", "");
|
return -1;
|
||||||
return Integer.parseInt(result);
|
}
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(release.replace(".", ""));
|
||||||
|
} catch (NumberFormatException invalid) {
|
||||||
|
return -1;
|
||||||
}
|
}
|
||||||
return -1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getMCVersion() {
|
public int getMCVersion() {
|
||||||
|
|||||||
+58
-1
@@ -55,6 +55,7 @@ import java.util.Set;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.TimeoutException;
|
import java.util.concurrent.TimeoutException;
|
||||||
@@ -73,6 +74,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
|||||||
private volatile UUID overworldEntryAwaitingVerification;
|
private volatile UUID overworldEntryAwaitingVerification;
|
||||||
private volatile World overworldEntryWorld;
|
private volatile World overworldEntryWorld;
|
||||||
private volatile boolean paperEntryListenerRegistered;
|
private volatile boolean paperEntryListenerRegistered;
|
||||||
|
private final Object stagingMonitor = new Object();
|
||||||
|
private boolean stagingAdmissionOpen = true;
|
||||||
|
private StagingAdmission activeStaging;
|
||||||
|
|
||||||
public PendingWorldReplacementManager(Iris plugin) {
|
public PendingWorldReplacementManager(Iris plugin) {
|
||||||
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
||||||
@@ -135,7 +139,7 @@ public final class PendingWorldReplacementManager implements Listener {
|
|||||||
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
|
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
|
||||||
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
|
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
|
||||||
requiredWorldKey.toString()
|
requiredWorldKey.toString()
|
||||||
)) {
|
); StagingAdmission stagingAdmission = admitStaging(requiredWorldKey)) {
|
||||||
if (findTransaction(requiredWorldSlotKey) != null) {
|
if (findTransaction(requiredWorldSlotKey) != null) {
|
||||||
throw new IOException("A replacement is already pending for " + requiredWorldKey + ".");
|
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() {
|
public synchronized void processPendingStartupReplacements() {
|
||||||
ArrayList<String> failures = new ArrayList<>();
|
ArrayList<String> failures = new ArrayList<>();
|
||||||
ArrayList<String> restartBoundaries = new ArrayList<>();
|
ArrayList<String> restartBoundaries = new ArrayList<>();
|
||||||
@@ -993,6 +1020,17 @@ public final class PendingWorldReplacementManager implements Listener {
|
|||||||
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
|
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 {
|
private synchronized void loadOverworldEntryGuard() throws IOException {
|
||||||
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
|
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
|
||||||
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
|
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
|
||||||
@@ -1157,6 +1195,25 @@ public final class PendingWorldReplacementManager implements Listener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final class StagingAdmission implements AutoCloseable {
|
||||||
|
private final NamespacedKey worldKey;
|
||||||
|
private final CountDownLatch finished = new CountDownLatch(1);
|
||||||
|
|
||||||
|
private StagingAdmission(NamespacedKey worldKey) {
|
||||||
|
this.worldKey = worldKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
synchronized (stagingMonitor) {
|
||||||
|
if (activeStaging == this) {
|
||||||
|
activeStaging = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finished.countDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static final class RestartBoundaryRequired extends IOException {
|
private static final class RestartBoundaryRequired extends IOException {
|
||||||
private RestartBoundaryRequired(String message) {
|
private RestartBoundaryRequired(String message) {
|
||||||
super(message);
|
super(message);
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package art.arcane.iris.core.agent;
|
||||||
|
|
||||||
|
import java.lang.foreign.Arena;
|
||||||
|
import java.lang.foreign.FunctionDescriptor;
|
||||||
|
import java.lang.foreign.Linker;
|
||||||
|
import java.lang.foreign.MemorySegment;
|
||||||
|
import java.lang.foreign.ValueLayout;
|
||||||
|
import java.lang.invoke.MethodHandle;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public final class AttachSignal {
|
||||||
|
private static final int SIGQUIT = 3;
|
||||||
|
private static final int SIGTERM = 15;
|
||||||
|
private static final long ACTION_BYTES = 256;
|
||||||
|
private static final long SIG_IGN = 1L;
|
||||||
|
|
||||||
|
private AttachSignal() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean restoreJvmHandler() {
|
||||||
|
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Linker linker = Linker.nativeLinker();
|
||||||
|
MethodHandle sigaction = linker.downcallHandle(
|
||||||
|
linker.defaultLookup().find("sigaction")
|
||||||
|
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
|
||||||
|
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
|
||||||
|
try (Arena arena = Arena.ofConfined()) {
|
||||||
|
MemorySegment jvm = arena.allocate(ACTION_BYTES);
|
||||||
|
MemorySegment quit = arena.allocate(ACTION_BYTES);
|
||||||
|
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|
||||||
|
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
|
||||||
|
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
|
||||||
|
}
|
||||||
|
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
|
||||||
|
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
|
||||||
|
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (RuntimeException | Error failure) {
|
||||||
|
throw failure;
|
||||||
|
} catch (Throwable failure) {
|
||||||
|
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -510,7 +510,7 @@ public class CommandIris implements DirectorExecutor {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||||
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
|
||||||
try {
|
try {
|
||||||
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
||||||
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
|
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
|
||||||
@@ -522,6 +522,8 @@ public class CommandIris implements DirectorExecutor {
|
|||||||
if (!Boolean.TRUE.equals(evacuated)) {
|
if (!Boolean.TRUE.equals(evacuated)) {
|
||||||
return CompletableFuture.completedFuture(false);
|
return CompletableFuture.completedFuture(false);
|
||||||
}
|
}
|
||||||
|
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
||||||
|
maintenanceEntered.set(true);
|
||||||
return WorldLifecycleService.get().unloadAsync(world, true);
|
return WorldLifecycleService.get().unloadAsync(world, true);
|
||||||
})
|
})
|
||||||
.thenCompose(unloaded -> {
|
.thenCompose(unloaded -> {
|
||||||
@@ -536,7 +538,9 @@ public class CommandIris implements DirectorExecutor {
|
|||||||
});
|
});
|
||||||
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
|
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
|
||||||
.whenComplete((unloaded, throwable) -> {
|
.whenComplete((unloaded, throwable) -> {
|
||||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
if (maintenanceEntered.get()) {
|
||||||
|
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||||
|
}
|
||||||
lease.close();
|
lease.close();
|
||||||
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
|
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
|
||||||
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
|
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
|
||||||
@@ -545,7 +549,9 @@ public class CommandIris implements DirectorExecutor {
|
|||||||
J.s(response);
|
J.s(response);
|
||||||
});
|
});
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
if (maintenanceEntered.get()) {
|
||||||
|
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||||
|
}
|
||||||
lease.close();
|
lease.close();
|
||||||
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_FAILED_UNLOAD_WORLD_3, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
|
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);
|
Iris.reportError("Failed to unload world \"" + world.getName() + "\".", e);
|
||||||
|
|||||||
+20
-11
@@ -24,9 +24,10 @@ public class IrisShutdownOrderingTest {
|
|||||||
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
|
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
|
||||||
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
|
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
|
||||||
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
|
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
|
||||||
String shutdownHook = section(source, "private void runShutdownHook()", "private boolean awaitServerShutdownBoundary");
|
String shutdownHook = section(source, "private void runShutdownHook()", "private void finishRuntimeAfterServerShutdown");
|
||||||
String finisher = section(source, "private void startPostStopFinisher()", "static boolean awaitServerThreadTermination");
|
String boundaryFinish = section(source, "private void finishRuntimeAfterServerShutdown", "private boolean awaitServerShutdownBoundary");
|
||||||
String serverJoin = section(source, "static boolean awaitServerThreadTermination", "private void runShutdownHook");
|
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 generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
|
||||||
String generatorQuiesce = section(generatorSource,
|
String generatorQuiesce = section(generatorSource,
|
||||||
"public void quiesceForServerShutdown()", "public boolean isStudio()");
|
"public void quiesceForServerShutdown()", "public boolean isStudio()");
|
||||||
@@ -43,17 +44,19 @@ public class IrisShutdownOrderingTest {
|
|||||||
"startupBoundaryRestart.get()",
|
"startupBoundaryRestart.get()",
|
||||||
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
|
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
|
||||||
"return;",
|
"return;",
|
||||||
"awaitServerShutdownBoundary()",
|
"finishRuntimeAfterServerShutdown(\"shutdown-hook\")");
|
||||||
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
|
|
||||||
assertOrdered(finisher,
|
assertOrdered(finisher,
|
||||||
|
"finishRuntimeAfterServerShutdown(\"post-server-stop\")",
|
||||||
"finisher.setDaemon(false)",
|
"finisher.setDaemon(false)",
|
||||||
"finisher.start()");
|
"finisher.start()");
|
||||||
assertOrdered(finisher,
|
assertOrdered(boundaryFinish,
|
||||||
"awaitServerThreadTermination(activeServerThread)",
|
"awaitServerShutdownBoundary()",
|
||||||
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
|
"return;",
|
||||||
assertOrdered(serverJoin,
|
"finishDeferredRuntimeTeardown(reason, 30L)");
|
||||||
"serverThread == Thread.currentThread()",
|
assertTrue("A missing shutdown boundary must retain the runtime",
|
||||||
"serverThread.join()");
|
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",
|
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
|
||||||
quiesce.contains("generator.quiesceForServerShutdown()"));
|
quiesce.contains("generator.quiesceForServerShutdown()"));
|
||||||
assertOrdered(quiesce,
|
assertOrdered(quiesce,
|
||||||
@@ -63,6 +66,12 @@ public class IrisShutdownOrderingTest {
|
|||||||
assertOrdered(onDisable,
|
assertOrdered(onDisable,
|
||||||
"quiesceRuntimeForServerShutdown(\"onDisable\")",
|
"quiesceRuntimeForServerShutdown(\"onDisable\")",
|
||||||
"super.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",
|
assertFalse("Server-stop quiescence must not begin generator close before Paper's boundary",
|
||||||
generatorQuiesce.contains("closing = true"));
|
generatorQuiesce.contains("closing = true"));
|
||||||
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
|
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package art.arcane.iris;
|
||||||
|
|
||||||
|
import org.bukkit.plugin.PluginDescriptionFile;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.mockito.Answers.CALLS_REAL_METHODS;
|
||||||
|
import static org.mockito.Mockito.doReturn;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
public class IrisVersionNumberTest {
|
||||||
|
@Test
|
||||||
|
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
|
||||||
|
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
|
||||||
|
assertEquals(version, 433, plugin(version).getIrisVersion());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void processedPluginMetadataProvidesAValidEngineVersion() throws Exception {
|
||||||
|
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
|
||||||
|
assertNotNull(stream);
|
||||||
|
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||||
|
doReturn(new PluginDescriptionFile(stream)).when(plugin).getDescription();
|
||||||
|
|
||||||
|
assertNotEquals(-1, plugin.getIrisVersion());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
|
||||||
|
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
|
||||||
|
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
|
||||||
|
assertEquals(version, -1, plugin(version).getIrisVersion());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Iris plugin(String version) {
|
||||||
|
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||||
|
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
|
||||||
|
return plugin;
|
||||||
|
}
|
||||||
|
}
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
package art.arcane.iris.core;
|
||||||
|
|
||||||
|
import art.arcane.iris.Iris;
|
||||||
|
import org.bukkit.NamespacedKey;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertThrows;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
||||||
|
public class PendingWorldReplacementAdmissionTest {
|
||||||
|
private static final long STATE_TIMEOUT_SECONDS = 5L;
|
||||||
|
private static final long JOIN_TIMEOUT_SECONDS = 10L;
|
||||||
|
private static final long STATE_POLL_MILLIS = 5L;
|
||||||
|
|
||||||
|
private final NamespacedKey worldKey = NamespacedKey.minecraft("overworld");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shutdownDoesNotWaitWhenNothingIsStaging() throws Exception {
|
||||||
|
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||||
|
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
|
||||||
|
|
||||||
|
shutdown.start();
|
||||||
|
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
|
||||||
|
|
||||||
|
assertFalse(shutdown.isAlive());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shutdownRejectsReplacementsThatStartAfterIt() throws Exception {
|
||||||
|
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||||
|
manager.awaitStagingForShutdown();
|
||||||
|
|
||||||
|
IOException rejected = assertThrows(IOException.class, () -> manager.admitStaging(worldKey));
|
||||||
|
|
||||||
|
assertTrue(rejected.getMessage().contains("shutting down"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shutdownWaitsForTheReplacementBeingStaged() throws Exception {
|
||||||
|
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||||
|
PendingWorldReplacementManager.StagingAdmission staging = manager.admitStaging(worldKey);
|
||||||
|
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
|
||||||
|
|
||||||
|
shutdown.start();
|
||||||
|
try {
|
||||||
|
awaitState(shutdown, Thread.State.WAITING);
|
||||||
|
assertTrue(shutdown.isAlive());
|
||||||
|
} finally {
|
||||||
|
staging.close();
|
||||||
|
}
|
||||||
|
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
|
||||||
|
|
||||||
|
assertFalse(shutdown.isAlive());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void awaitState(Thread thread, Thread.State state) throws InterruptedException {
|
||||||
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(STATE_TIMEOUT_SECONDS);
|
||||||
|
while (thread.getState() != state) {
|
||||||
|
if (System.nanoTime() > deadline) {
|
||||||
|
throw new AssertionError(thread.getName() + " never reached " + state + "; it is " + thread.getState());
|
||||||
|
}
|
||||||
|
Thread.sleep(STATE_POLL_MILLIS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package art.arcane.iris.core.agent;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.lang.foreign.Arena;
|
||||||
|
import java.lang.foreign.FunctionDescriptor;
|
||||||
|
import java.lang.foreign.Linker;
|
||||||
|
import java.lang.foreign.MemorySegment;
|
||||||
|
import java.lang.foreign.ValueLayout;
|
||||||
|
import java.lang.invoke.MethodHandle;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assume.assumeFalse;
|
||||||
|
|
||||||
|
public class AttachSignalTest {
|
||||||
|
private static final int SIGQUIT = 3;
|
||||||
|
private static final int SIGTERM = 15;
|
||||||
|
private static final long ACTION_BYTES = 256;
|
||||||
|
private static final MethodHandle SIGACTION = Linker.nativeLinker().downcallHandle(
|
||||||
|
Linker.nativeLinker().defaultLookup().find("sigaction").orElseThrow(),
|
||||||
|
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void aConsoleThatResetsQuitGetsTheJvmHandlerBack() throws Throwable {
|
||||||
|
assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"));
|
||||||
|
long jvmHandler = handler(SIGTERM);
|
||||||
|
assertNotEquals(0L, jvmHandler);
|
||||||
|
try (Arena arena = Arena.ofConfined()) {
|
||||||
|
MemorySegment original = arena.allocate(ACTION_BYTES);
|
||||||
|
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, MemorySegment.NULL, original));
|
||||||
|
try {
|
||||||
|
MemorySegment reset = arena.allocate(ACTION_BYTES);
|
||||||
|
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, reset, MemorySegment.NULL));
|
||||||
|
assertEquals(0L, handler(SIGQUIT));
|
||||||
|
|
||||||
|
assertTrue(AttachSignal.restoreJvmHandler());
|
||||||
|
|
||||||
|
assertEquals(jvmHandler, handler(SIGQUIT));
|
||||||
|
assertFalse(AttachSignal.restoreJvmHandler());
|
||||||
|
} finally {
|
||||||
|
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, original, MemorySegment.NULL));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long handler(int signal) throws Throwable {
|
||||||
|
try (Arena arena = Arena.ofConfined()) {
|
||||||
|
MemorySegment action = arena.allocate(ACTION_BYTES);
|
||||||
|
assertEquals(0, (int) SIGACTION.invokeExact(signal, MemorySegment.NULL, action));
|
||||||
|
return action.get(ValueLayout.JAVA_LONG, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -85,7 +85,7 @@ public class IrisPapiLifecycleTest {
|
|||||||
String source = source();
|
String source = source();
|
||||||
|
|
||||||
assertTrue("onDisable must tear the expansion down",
|
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",
|
assertTrue("the BileTools pre-unload hook must tear the expansion down",
|
||||||
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
|
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ public final class IrisFabricBootstrap implements ModInitializer {
|
|||||||
ServerLifecycleEvents.SERVER_STARTING.register((MinecraftServer server) -> ModdedEngineBootstrap.start(server));
|
ServerLifecycleEvents.SERVER_STARTING.register((MinecraftServer server) -> ModdedEngineBootstrap.start(server));
|
||||||
ServerLifecycleEvents.SERVER_STARTED.register((MinecraftServer server) -> ModdedEngineBootstrap.serverStarted(server));
|
ServerLifecycleEvents.SERVER_STARTED.register((MinecraftServer server) -> ModdedEngineBootstrap.serverStarted(server));
|
||||||
ServerLifecycleEvents.SERVER_STOPPING.register((MinecraftServer server) -> ModdedEngineBootstrap.stop());
|
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.LOAD.register((MinecraftServer server, ServerLevel level) -> ModdedEngineBootstrap.levelLoaded(level));
|
||||||
ServerLevelEvents.UNLOAD.register((MinecraftServer server, ServerLevel level) -> ModdedEngineBootstrap.levelUnloaded(level));
|
ServerLevelEvents.UNLOAD.register((MinecraftServer server, ServerLevel level) -> ModdedEngineBootstrap.levelUnloaded(level));
|
||||||
CommandRegistrationCallback.EVENT.register((CommandDispatcher<CommandSourceStack> dispatcher, CommandBuildContext buildContext, Commands.CommandSelection selection) -> IrisModdedCommands.register(dispatcher));
|
CommandRegistrationCallback.EVENT.register((CommandDispatcher<CommandSourceStack> dispatcher, CommandBuildContext buildContext, Commands.CommandSelection selection) -> IrisModdedCommands.register(dispatcher));
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import net.minecraftforge.event.level.LevelEvent;
|
|||||||
import net.minecraftforge.event.server.ServerAboutToStartEvent;
|
import net.minecraftforge.event.server.ServerAboutToStartEvent;
|
||||||
import net.minecraftforge.event.server.ServerStartedEvent;
|
import net.minecraftforge.event.server.ServerStartedEvent;
|
||||||
import net.minecraftforge.event.server.ServerStartingEvent;
|
import net.minecraftforge.event.server.ServerStartingEvent;
|
||||||
|
import net.minecraftforge.event.server.ServerStoppedEvent;
|
||||||
import net.minecraftforge.event.server.ServerStoppingEvent;
|
import net.minecraftforge.event.server.ServerStoppingEvent;
|
||||||
import net.minecraftforge.api.distmarker.Dist;
|
import net.minecraftforge.api.distmarker.Dist;
|
||||||
import net.minecraftforge.common.loot.IGlobalLootModifier;
|
import net.minecraftforge.common.loot.IGlobalLootModifier;
|
||||||
@@ -82,6 +83,7 @@ public final class IrisForgeBootstrap {
|
|||||||
ServerStartingEvent.BUS.addListener((ServerStartingEvent event) -> ModdedEngineBootstrap.start(event.getServer()));
|
ServerStartingEvent.BUS.addListener((ServerStartingEvent event) -> ModdedEngineBootstrap.start(event.getServer()));
|
||||||
ServerStartedEvent.BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
|
ServerStartedEvent.BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
|
||||||
ServerStoppingEvent.BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
|
ServerStoppingEvent.BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
|
||||||
|
ServerStoppedEvent.BUS.addListener((ServerStoppedEvent event) -> ModdedEngineBootstrap.stopped());
|
||||||
LevelEvent.Load.BUS.addListener((LevelEvent.Load event) -> {
|
LevelEvent.Load.BUS.addListener((LevelEvent.Load event) -> {
|
||||||
if (event.getLevel() instanceof ServerLevel level) {
|
if (event.getLevel() instanceof ServerLevel level) {
|
||||||
ModdedEngineBootstrap.levelLoaded(level);
|
ModdedEngineBootstrap.levelLoaded(level);
|
||||||
|
|||||||
+1
-14
@@ -65,7 +65,6 @@ public final class ModdedDimensionManager {
|
|||||||
private static final ConcurrentHashMap<String, Handle> HANDLES = new ConcurrentHashMap<>();
|
private static final ConcurrentHashMap<String, Handle> HANDLES = new ConcurrentHashMap<>();
|
||||||
private static final TicketType TELEPORT_WARM_TICKET = new TicketType(TicketType.NO_TIMEOUT,
|
private static final TicketType TELEPORT_WARM_TICKET = new TicketType(TicketType.NO_TIMEOUT,
|
||||||
TicketType.FLAG_LOADING | TicketType.FLAG_KEEP_DIMENSION_ACTIVE);
|
TicketType.FLAG_LOADING | TicketType.FLAG_KEEP_DIMENSION_ACTIVE);
|
||||||
private static final long TELEPORT_TIMEOUT_SECONDS = 10L;
|
|
||||||
private static volatile ModdedServerAccess access;
|
private static volatile ModdedServerAccess access;
|
||||||
|
|
||||||
private ModdedDimensionManager() {
|
private ModdedDimensionManager() {
|
||||||
@@ -265,18 +264,6 @@ public final class ModdedDimensionManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static CompletableFuture<Boolean> teleportAsync(
|
|
||||||
ServerPlayer player,
|
|
||||||
MinecraftServer server,
|
|
||||||
String dimensionId,
|
|
||||||
double x,
|
|
||||||
double y,
|
|
||||||
double z
|
|
||||||
) {
|
|
||||||
return teleportAsync(player, server, dimensionId, x, y, z,
|
|
||||||
System.nanoTime() + TimeUnit.SECONDS.toNanos(TELEPORT_TIMEOUT_SECONDS));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static CompletableFuture<Boolean> teleportAsync(
|
public static CompletableFuture<Boolean> teleportAsync(
|
||||||
ServerPlayer player,
|
ServerPlayer player,
|
||||||
MinecraftServer server,
|
MinecraftServer server,
|
||||||
@@ -513,7 +500,7 @@ public final class ModdedDimensionManager {
|
|||||||
return new TimeoutException("Teleport into " + level.dimension().identifier()
|
return new TimeoutException("Teleport into " + level.dimension().identifier()
|
||||||
+ " at " + ModdedTeleportBounds.blockCoordinate(x) + ","
|
+ " at " + ModdedTeleportBounds.blockCoordinate(x) + ","
|
||||||
+ ModdedTeleportBounds.blockCoordinate(z)
|
+ ModdedTeleportBounds.blockCoordinate(z)
|
||||||
+ " exceeded " + TELEPORT_TIMEOUT_SECONDS + " seconds.");
|
+ " did not finish before its deadline.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void runOnServer(MinecraftServer server, Runnable task) {
|
private static void runOnServer(MinecraftServer server, Runnable task) {
|
||||||
|
|||||||
+76
-10
@@ -58,6 +58,8 @@ import net.minecraft.world.level.levelgen.Heightmap;
|
|||||||
import net.minecraft.world.level.storage.LevelData;
|
import net.minecraft.world.level.storage.LevelData;
|
||||||
|
|
||||||
import java.util.ArrayDeque;
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
public final class ModdedEngineBootstrap {
|
public final class ModdedEngineBootstrap {
|
||||||
private static final String[] CORE_SELF_TEST_CLASSES = {
|
private static final String[] CORE_SELF_TEST_CLASSES = {
|
||||||
@@ -66,12 +68,17 @@ public final class ModdedEngineBootstrap {
|
|||||||
"art.arcane.iris.core.loader.IrisData"
|
"art.arcane.iris.core.loader.IrisData"
|
||||||
};
|
};
|
||||||
private static final Object LOCK = new Object();
|
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 final ModdedServiceManager UNBOUND_SERVICE_MANAGER = new ModdedServiceManager();
|
||||||
private static volatile ModdedLoader loader;
|
private static volatile ModdedLoader loader;
|
||||||
private static volatile BoundRuntime runtime;
|
private static volatile BoundRuntime runtime;
|
||||||
private static volatile MinecraftServer currentServer;
|
private static volatile MinecraftServer currentServer;
|
||||||
private static volatile MinecraftServer spawnCaptureServer;
|
private static volatile MinecraftServer spawnCaptureServer;
|
||||||
private static volatile boolean initialSpawnWasDefault;
|
private static volatile boolean initialSpawnWasDefault;
|
||||||
|
private static volatile boolean stoppedPending;
|
||||||
|
private static volatile Thread stoppingThread;
|
||||||
|
|
||||||
private ModdedEngineBootstrap() {
|
private ModdedEngineBootstrap() {
|
||||||
}
|
}
|
||||||
@@ -96,10 +103,12 @@ public final class ModdedEngineBootstrap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void start(MinecraftServer server) {
|
public static void start(MinecraftServer server) {
|
||||||
|
finishPreviousServer("server start");
|
||||||
|
registerExitFlush();
|
||||||
captureInitialSpawn(server);
|
captureInitialSpawn(server);
|
||||||
currentServer = server;
|
currentServer = server;
|
||||||
bind();
|
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
|
// closed, MultiBurst falls back to a same-thread executor, so a second world load
|
||||||
// without reopen() would silently run every burst inline.
|
// without reopen() would silently run every burst inline.
|
||||||
MultiBurst.burst.reopen();
|
MultiBurst.burst.reopen();
|
||||||
@@ -125,6 +134,7 @@ public final class ModdedEngineBootstrap {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void serverAboutToStart(MinecraftServer server) {
|
public static void serverAboutToStart(MinecraftServer server) {
|
||||||
|
finishPreviousServer("server start");
|
||||||
captureInitialSpawn(server);
|
captureInitialSpawn(server);
|
||||||
ModdedStartup.prepareForStartup();
|
ModdedStartup.prepareForStartup();
|
||||||
}
|
}
|
||||||
@@ -153,20 +163,16 @@ public final class ModdedEngineBootstrap {
|
|||||||
try {
|
try {
|
||||||
generator.unbindEngine(level);
|
generator.unbindEngine(level);
|
||||||
} catch (Throwable exception) {
|
} 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);
|
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() {
|
public static void stop() {
|
||||||
MinecraftServer stoppingServer = currentServer;
|
MinecraftServer stoppingServer = currentServer;
|
||||||
|
stoppingThread = Thread.currentThread();
|
||||||
|
stoppedPending = true;
|
||||||
Throwable failure = null;
|
Throwable failure = null;
|
||||||
failure = runStopStage(failure, "pack downloads", IrisModdedCommands::shutdownDownloads);
|
failure = runStopStage(failure, "pack downloads", IrisModdedCommands::shutdownDownloads);
|
||||||
failure = runStopStage(failure, "world check", () -> ModdedWorldCheck.serverStopped(stoppingServer));
|
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, "studio commands", ModdedStudioCommands::clear);
|
||||||
failure = runStopStage(failure, "gui host", ModdedGuiHost::clear);
|
failure = runStopStage(failure, "gui host", ModdedGuiHost::clear);
|
||||||
failure = runStopStage(failure, "services", () -> services().disableAll());
|
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, "world engines", ModdedWorldEngines::shutdown);
|
||||||
failure = runStopStage(failure, "primary world router", ModdedPrimaryWorldRouter::clear);
|
failure = runStopStage(failure, "primary world router", ModdedPrimaryWorldRouter::clear);
|
||||||
failure = runStopStage(failure, "dimension manager", ModdedDimensionManager::clear);
|
failure = runStopStage(failure, "dimension manager", ModdedDimensionManager::clear);
|
||||||
@@ -201,10 +263,14 @@ public final class ModdedEngineBootstrap {
|
|||||||
spawnCaptureServer = null;
|
spawnCaptureServer = null;
|
||||||
initialSpawnWasDefault = false;
|
initialSpawnWasDefault = false;
|
||||||
});
|
});
|
||||||
|
reportStopFailure("stopped", failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reportStopFailure(String phase, Throwable failure) {
|
||||||
if (failure != null) {
|
if (failure != null) {
|
||||||
// The shutdown path must not propagate: propagating aborts the remaining loader stop handlers and
|
// 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.
|
// 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -101,7 +101,8 @@ public final class ModdedPrimaryWorldRouter {
|
|||||||
primary,
|
primary,
|
||||||
player.getX(),
|
player.getX(),
|
||||||
Double.MIN_VALUE,
|
Double.MIN_VALUE,
|
||||||
player.getZ());
|
player.getZ(),
|
||||||
|
ModdedTeleportDeadline.fromNow());
|
||||||
teleport.whenComplete((success, failure) -> {
|
teleport.whenComplete((success, failure) -> {
|
||||||
inFlight.remove(id);
|
inFlight.remove(id);
|
||||||
if (Boolean.TRUE.equals(success) && failure == null) {
|
if (Boolean.TRUE.equals(success) && failure == null) {
|
||||||
|
|||||||
@@ -192,7 +192,8 @@ public final class ModdedScheduler implements PlatformScheduler {
|
|||||||
mainQueue.clear();
|
mainQueue.clear();
|
||||||
delayedQueue.clear();
|
delayedQueue.clear();
|
||||||
mainThread = null;
|
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();
|
ModdedServerLevels.forget();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
/*
|
||||||
|
* Iris is a World Generator for Minecraft Servers
|
||||||
|
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||||
|
*
|
||||||
|
* This program is free software: you can redistribute it and/or modify
|
||||||
|
* it under the terms of the GNU General Public License as published by
|
||||||
|
* the Free Software Foundation, either version 3 of the License, or
|
||||||
|
* (at your option) any later version.
|
||||||
|
*
|
||||||
|
* This program is distributed in the hope that it will be useful,
|
||||||
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
* GNU General Public License for more details.
|
||||||
|
*
|
||||||
|
* You should have received a copy of the GNU General Public License
|
||||||
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package art.arcane.iris.modded;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deadline for a teleport that waits on its destination chunk. The first chunk of a cold dimension also loads the
|
||||||
|
* pack and binds the engine; the deadline only bounds a destination whose chunk never completes.
|
||||||
|
*/
|
||||||
|
public final class ModdedTeleportDeadline {
|
||||||
|
private static final long DEADLINE_SECONDS = 120L;
|
||||||
|
|
||||||
|
private ModdedTeleportDeadline() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long fromNow() {
|
||||||
|
return System.nanoTime() + TimeUnit.SECONDS.toNanos(DEADLINE_SECONDS);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -225,9 +225,9 @@ public final class ModdedWorldEngines {
|
|||||||
Engine engine = entry.getValue();
|
Engine engine = entry.getValue();
|
||||||
try {
|
try {
|
||||||
// Latch the generator's unloading flag BEFORE closing (unbindEngine sets it,
|
// Latch the generator's unloading flag BEFORE closing (unbindEngine sets it,
|
||||||
// then evicts): chunk-system drain work running after this stage would
|
// then evicts): late chunk work would otherwise see a closed engine and
|
||||||
// otherwise see a closed engine and silently rebuild a fresh engine + Mantle
|
// silently rebuild a fresh engine + Mantle that no teardown stage ever
|
||||||
// that no teardown stage ever closes, writing plates after the final save.
|
// closes, writing plates after the final save.
|
||||||
if (level.getChunkSource().getGenerator() instanceof IrisModdedChunkGenerator generator) {
|
if (level.getChunkSource().getGenerator() instanceof IrisModdedChunkGenerator generator) {
|
||||||
generator.unbindEngine(level);
|
generator.unbindEngine(level);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+58
-19
@@ -36,6 +36,7 @@ import art.arcane.iris.modded.ModdedForcedDatapack;
|
|||||||
import art.arcane.iris.modded.ModdedLoader;
|
import art.arcane.iris.modded.ModdedLoader;
|
||||||
import art.arcane.iris.modded.ModdedScheduler;
|
import art.arcane.iris.modded.ModdedScheduler;
|
||||||
import art.arcane.iris.modded.ModdedServerLevels;
|
import art.arcane.iris.modded.ModdedServerLevels;
|
||||||
|
import art.arcane.iris.modded.ModdedTeleportDeadline;
|
||||||
import art.arcane.iris.modded.ModdedWorldgenIds;
|
import art.arcane.iris.modded.ModdedWorldgenIds;
|
||||||
import art.arcane.iris.spi.IrisLogging;
|
import art.arcane.iris.spi.IrisLogging;
|
||||||
import art.arcane.volmlib.util.collection.KMap;
|
import art.arcane.volmlib.util.collection.KMap;
|
||||||
@@ -58,6 +59,7 @@ import java.util.Locale;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.TreeMap;
|
import java.util.TreeMap;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.CompletionException;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import art.arcane.volmlib.util.localization.MessageArgument;
|
import art.arcane.volmlib.util.localization.MessageArgument;
|
||||||
@@ -135,7 +137,8 @@ public final class IrisModdedCommands {
|
|||||||
dimensionId,
|
dimensionId,
|
||||||
8.5D,
|
8.5D,
|
||||||
Double.MIN_VALUE,
|
Double.MIN_VALUE,
|
||||||
8.5D);
|
8.5D,
|
||||||
|
ModdedTeleportDeadline.fromNow());
|
||||||
teleport.whenComplete((success, failure) -> {
|
teleport.whenComplete((success, failure) -> {
|
||||||
if (Boolean.TRUE.equals(success) && failure == null) {
|
if (Boolean.TRUE.equals(success) && failure == null) {
|
||||||
return;
|
return;
|
||||||
@@ -144,14 +147,43 @@ public final class IrisModdedCommands {
|
|||||||
ModdedIrisLog.error("Iris teleport into '{}' failed for {}",
|
ModdedIrisLog.error("Iris teleport into '{}' failed for {}",
|
||||||
dimensionId, player.getUUID(), failure);
|
dimensionId, player.getUUID(), failure);
|
||||||
}
|
}
|
||||||
server.execute(() -> fail(source, IrisLanguage.plain(
|
server.execute(() -> fail(source, teleportFailure(dimensionId, player.getScoreboardName(), failure,
|
||||||
ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORT_FAILED_DIMENSION_IS_NOT_LOADED,
|
ModdedDimensionManager.level(server, dimensionId) != null,
|
||||||
MessageArgument.untrusted("dimensionId", dimensionId))));
|
server.getPlayerList().getPlayer(player.getUUID()) != null)));
|
||||||
});
|
});
|
||||||
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORTING, MessageArgument.untrusted("value", player.getScoreboardName()), MessageArgument.untrusted("dimensionId", dimensionId)));
|
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_TELEPORTING, MessageArgument.untrusted("value", player.getScoreboardName()), MessageArgument.untrusted("dimensionId", dimensionId)));
|
||||||
return 1;
|
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) {
|
static int evacuate(CommandSourceStack source, ServerLevel target) {
|
||||||
MinecraftServer server = source.getServer();
|
MinecraftServer server = source.getServer();
|
||||||
ServerLevel level = target != null ? target : source.getLevel();
|
ServerLevel level = target != null ? target : source.getLevel();
|
||||||
@@ -262,20 +294,7 @@ public final class IrisModdedCommands {
|
|||||||
&& !irisGenerator.dimensionKey().contains(filter)) {
|
&& !irisGenerator.dimensionKey().contains(filter)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Engine engine = irisGenerator.engineIfBound();
|
lines.add(worldRow(dimensionId, irisGenerator.dimensionKey(), irisGenerator.engineIfBound(), showSeed, irisGenerator.importedFeaturesStatus()));
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_LOADED_DIMENSIONS_IRIS, MessageArgument.untrusted("total", total), MessageArgument.untrusted("iris", iris)));
|
ok(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_LOADED_DIMENSIONS_IRIS, MessageArgument.untrusted("total", total), MessageArgument.untrusted("iris", iris)));
|
||||||
if (lines.isEmpty()) {
|
if (lines.isEmpty()) {
|
||||||
@@ -292,6 +311,26 @@ public final class IrisModdedCommands {
|
|||||||
return 1;
|
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) {
|
static int seed(CommandSourceStack source) {
|
||||||
ServerLevel level = source.getLevel();
|
ServerLevel level = source.getLevel();
|
||||||
Engine engine = engineFor(level);
|
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));
|
fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_14));
|
||||||
return 0;
|
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())));
|
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;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -25,6 +25,7 @@ import art.arcane.iris.engine.framework.Engine;
|
|||||||
import art.arcane.iris.engine.framework.render.RenderType;
|
import art.arcane.iris.engine.framework.render.RenderType;
|
||||||
import art.arcane.iris.modded.ModdedDimensionManager;
|
import art.arcane.iris.modded.ModdedDimensionManager;
|
||||||
import art.arcane.iris.modded.ModdedIrisLog;
|
import art.arcane.iris.modded.ModdedIrisLog;
|
||||||
|
import art.arcane.iris.modded.ModdedTeleportDeadline;
|
||||||
import net.minecraft.server.MinecraftServer;
|
import net.minecraft.server.MinecraftServer;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
import net.minecraft.server.level.ServerPlayer;
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
@@ -37,7 +38,6 @@ import java.util.ArrayList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.CompletableFuture;
|
import java.util.concurrent.CompletableFuture;
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
public final class ModdedVisionOverlay implements GuiOverlay {
|
public final class ModdedVisionOverlay implements GuiOverlay {
|
||||||
@@ -103,7 +103,7 @@ public final class ModdedVisionOverlay implements GuiOverlay {
|
|||||||
blockX + 0.5D,
|
blockX + 0.5D,
|
||||||
surfaceY,
|
surfaceY,
|
||||||
blockZ + 0.5D,
|
blockZ + 0.5D,
|
||||||
System.nanoTime() + TimeUnit.SECONDS.toNanos(10L));
|
ModdedTeleportDeadline.fromNow());
|
||||||
UUID playerId = player.getUUID();
|
UUID playerId = player.getUUID();
|
||||||
teleport.whenComplete((success, failure) -> {
|
teleport.whenComplete((success, failure) -> {
|
||||||
if (failure != null) {
|
if (failure != null) {
|
||||||
|
|||||||
+69
-10
@@ -33,6 +33,7 @@ import art.arcane.iris.modded.api.ModdedBlockData;
|
|||||||
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
|
import art.arcane.iris.modded.api.ModdedCustomContentRegistry;
|
||||||
import art.arcane.iris.spi.IrisLogging;
|
import art.arcane.iris.spi.IrisLogging;
|
||||||
import art.arcane.iris.util.project.matter.TileWrapper;
|
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.flag.MantleFlag;
|
||||||
import art.arcane.volmlib.util.mantle.runtime.Mantle;
|
import art.arcane.volmlib.util.mantle.runtime.Mantle;
|
||||||
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
|
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.MatterCavern;
|
||||||
import art.arcane.volmlib.util.matter.MatterUpdate;
|
import art.arcane.volmlib.util.matter.MatterUpdate;
|
||||||
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
|
import art.arcane.volmlib.util.scheduling.PrecisionStopwatch;
|
||||||
|
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.server.MinecraftServer;
|
import net.minecraft.server.MinecraftServer;
|
||||||
import net.minecraft.server.level.ServerLevel;
|
import net.minecraft.server.level.ServerLevel;
|
||||||
@@ -60,6 +62,7 @@ import java.util.concurrent.ExecutorService;
|
|||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.RejectedExecutionException;
|
import java.util.concurrent.RejectedExecutionException;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
|
||||||
public final class ModdedChunkUpdateService implements ModdedTickableService {
|
public final class ModdedChunkUpdateService implements ModdedTickableService {
|
||||||
private static final long PASS_PERIOD_MILLIS = 3_000L;
|
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;
|
int centerZ = player.blockPosition().getZ() >> 4;
|
||||||
for (int dx = -PLAYER_CHUNK_RADIUS; dx <= PLAYER_CHUNK_RADIUS; dx++) {
|
for (int dx = -PLAYER_CHUNK_RADIUS; dx <= PLAYER_CHUNK_RADIUS; dx++) {
|
||||||
for (int dz = -PLAYER_CHUNK_RADIUS; dz <= PLAYER_CHUNK_RADIUS; dz++) {
|
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) {
|
private void updateForcedChunks(Engine engine, ServerLevel level) {
|
||||||
for (long chunkKey : level.getForceLoadedChunks()) {
|
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);
|
updateChunk(engine, level, chunkX, chunkZ, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateChunk(Engine engine, ServerLevel level, int chunkX, int chunkZ) {
|
private void updatePassChunk(Engine engine, ServerLevel level, int chunkX, int chunkZ) {
|
||||||
updateChunk(engine, level, chunkX, chunkZ, true);
|
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) {
|
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) -> {
|
applyQueuedUpdates(chunk, (Integer x, Integer yf, Integer z) ->
|
||||||
if (v != null && v.isUpdate()) {
|
update(engine, level, x, yf + minHeight, z, baseX, baseZ, chunk));
|
||||||
update(engine, level, x, yf + minHeight, z, baseX, baseZ, chunk);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
chunk.deleteSlices(MatterUpdate.class);
|
|
||||||
engine.getMetrics().getUpdates().put(stopwatch.getMilliseconds());
|
engine.getMetrics().getUpdates().put(stopwatch.getMilliseconds());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void applyQueuedUpdates(MantleChunk<Matter> chunk, Consumer3<Integer, Integer, Integer> update) {
|
||||||
|
IntArrayList completed = new IntArrayList();
|
||||||
|
try {
|
||||||
|
chunk.iterate(MatterUpdate.class, (Integer x, Integer yf, Integer z, MatterUpdate v) -> {
|
||||||
|
if (v != null && v.isUpdate()) {
|
||||||
|
update.accept(x, yf, z);
|
||||||
|
completed.add(packUpdatePosition(x, yf, z));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RuntimeException | Error failure) {
|
||||||
|
forgetCompletedUpdates(chunk, completed, failure);
|
||||||
|
throw failure;
|
||||||
|
}
|
||||||
|
chunk.deleteSlices(MatterUpdate.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int packUpdatePosition(int x, int yf, int z) {
|
||||||
|
return (yf << 8) | ((x & 15) << 4) | (z & 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void forgetCompletedUpdates(MantleChunk<Matter> chunk, IntArrayList completed, Throwable failure) {
|
||||||
|
try {
|
||||||
|
for (int index = 0; index < completed.size(); index++) {
|
||||||
|
int position = completed.getInt(index);
|
||||||
|
int yf = position >>> 8;
|
||||||
|
Matter section = chunk.get(yf >> 4);
|
||||||
|
if (section != null && section.hasSlice(MatterUpdate.class)) {
|
||||||
|
section.<MatterUpdate>getSlice(MatterUpdate.class)
|
||||||
|
.set((position >> 4) & 15, yf & 15, position & 15, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (RuntimeException | Error cleanupFailure) {
|
||||||
|
if (cleanupFailure != failure) {
|
||||||
|
failure.addSuppressed(cleanupFailure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void update(Engine engine, ServerLevel level, int x, int y, int z, int baseX, int baseZ, MantleChunk<Matter> chunk) {
|
private void update(Engine engine, ServerLevel level, int x, int y, int z, int baseX, int baseZ, MantleChunk<Matter> chunk) {
|
||||||
if (y < level.getMinY() || y >= level.getMaxY()) {
|
if (y < level.getMinY() || y >= level.getMaxY()) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
package art.arcane.iris.modded;
|
||||||
|
|
||||||
|
import art.arcane.iris.core.IrisSettings;
|
||||||
|
import art.arcane.iris.modded.command.IrisModdedCommands;
|
||||||
|
import art.arcane.iris.util.common.parallel.MultiBurst;
|
||||||
|
import net.minecraft.SharedConstants;
|
||||||
|
import net.minecraft.server.Bootstrap;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotSame;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.mockStatic;
|
||||||
|
|
||||||
|
public class ModdedEngineBootstrapShutdownTest {
|
||||||
|
private static final long WORKER_TIMEOUT_SECONDS = 10L;
|
||||||
|
private static final Callable<Thread> RUNNING_THREAD = Thread::currentThread;
|
||||||
|
|
||||||
|
private IrisSettings previousSettings;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void bootstrapMinecraftRegistries() {
|
||||||
|
SharedConstants.tryDetectVersion();
|
||||||
|
Bootstrap.bootStrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void openRuntime() {
|
||||||
|
previousSettings = IrisSettings.settings;
|
||||||
|
IrisSettings.settings = new IrisSettings();
|
||||||
|
reopenBurstPools();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void restoreRuntime() {
|
||||||
|
reopenBurstPools();
|
||||||
|
IrisModdedCommands.openDownloadAdmission();
|
||||||
|
IrisSettings.settings = previousSettings;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void serverStoppingKeepsTheGenerationPoolsOpenUntilServerStopped() throws Exception {
|
||||||
|
ModdedEngineBootstrap.stop();
|
||||||
|
|
||||||
|
assertNotSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
||||||
|
|
||||||
|
ModdedEngineBootstrap.stopped();
|
||||||
|
|
||||||
|
assertSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void nextServerStartClosesWhatAServerThatNeverReachedStoppedLeftOpen() throws Exception {
|
||||||
|
ModdedEngineBootstrap.stop();
|
||||||
|
|
||||||
|
try (MockedStatic<ModdedStartup> startup = mockStatic(ModdedStartup.class)) {
|
||||||
|
ModdedEngineBootstrap.serverAboutToStart(mock(MinecraftServer.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void serverStartLeavesTheGenerationPoolsAloneWhenTheServerStoppedNormally() throws Exception {
|
||||||
|
ModdedEngineBootstrap.stop();
|
||||||
|
ModdedEngineBootstrap.stopped();
|
||||||
|
MultiBurst.burst.reopen();
|
||||||
|
|
||||||
|
try (MockedStatic<ModdedStartup> startup = mockStatic(ModdedStartup.class)) {
|
||||||
|
ModdedEngineBootstrap.serverAboutToStart(mock(MinecraftServer.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNotSame(Thread.currentThread(), MultiBurst.burst.submit(RUNNING_THREAD).get(WORKER_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void reopenBurstPools() {
|
||||||
|
MultiBurst.burst.reopen();
|
||||||
|
MultiBurst.ioBurst.reopen();
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-4
@@ -120,10 +120,10 @@ public class ModdedGenerationLeaseContractTest {
|
|||||||
|
|
||||||
String bootstrap = source("art/arcane/iris/modded/ModdedEngineBootstrap.java");
|
String bootstrap = source("art/arcane/iris/modded/ModdedEngineBootstrap.java");
|
||||||
String stop = method(bootstrap, "public static void stop()");
|
String stop = method(bootstrap, "public static void stop()");
|
||||||
int downloads = stop.indexOf("IrisModdedCommands::shutdownDownloads");
|
assertTrue(stop.contains("IrisModdedCommands::shutdownDownloads"));
|
||||||
int scheduler = stop.indexOf("scheduler::shutdown");
|
assertFalse(stop.contains("scheduler::shutdown"));
|
||||||
assertTrue(downloads >= 0);
|
String stopped = method(bootstrap, "private static void closeStoppedServer()");
|
||||||
assertTrue(scheduler > downloads);
|
assertTrue(stopped.contains("scheduler::shutdown"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+14
-8
@@ -141,21 +141,27 @@ public class ModdedLifecycleFailureContractTest {
|
|||||||
@Test
|
@Test
|
||||||
public void engineBootstrapResetsStartupExactlyOnceDuringStop() throws IOException {
|
public void engineBootstrapResetsStartupExactlyOnceDuringStop() throws IOException {
|
||||||
String source = source("ModdedEngineBootstrap.java");
|
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
|
@Test
|
||||||
public void engineBootstrapAttemptsEveryShutdownStageAndAggregatesFailures() throws IOException {
|
public void engineBootstrapAttemptsEveryShutdownStageAndAggregatesFailures() throws IOException {
|
||||||
String source = source("ModdedEngineBootstrap.java");
|
String source = source("ModdedEngineBootstrap.java");
|
||||||
String stop = method(source, "public static void stop(");
|
String stop = method(source, "public static void stop(");
|
||||||
|
String stopped = method(source, "private static void closeStoppedServer(");
|
||||||
|
|
||||||
assertBefore(stop, "\"services\"", "\"world engines\"");
|
assertTrue(stop.contains("\"services\""));
|
||||||
assertBefore(stop, "\"world engines\"", "\"dimension manager\"");
|
assertFalse(stop.contains("\"world engines\""));
|
||||||
assertBefore(stop, "\"server state\"", "if (failure != null)");
|
assertBefore(stopped, "\"world engines\"", "\"dimension manager\"");
|
||||||
|
assertBefore(stopped, "\"server state\"", "reportStopFailure(\"stopped\", failure);");
|
||||||
|
assertBefore(stop, "\"services\"", "reportStopFailure(\"stopping\", failure);");
|
||||||
assertFalse(stop.contains("throw"));
|
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(");
|
String runStage = method(source, "private static Throwable runStopStage(");
|
||||||
assertTrue(runStage.contains("catch (Throwable stageFailure)"));
|
assertTrue(runStage.contains("catch (Throwable stageFailure)"));
|
||||||
@@ -206,12 +212,12 @@ public class ModdedLifecycleFailureContractTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void loaderUnloadSurfacesCloseFailureAndDynamicRemovalUsesStrictEviction() throws IOException {
|
public void loaderUnloadLogsCloseFailureAndDynamicRemovalUsesStrictEviction() throws IOException {
|
||||||
String bootstrapSource = source("ModdedEngineBootstrap.java");
|
String bootstrapSource = source("ModdedEngineBootstrap.java");
|
||||||
String unload = method(bootstrapSource, "public static void levelUnloaded(ServerLevel level)");
|
String unload = method(bootstrapSource, "public static void levelUnloaded(ServerLevel level)");
|
||||||
String failure = catchBlock(unload);
|
String failure = catchBlock(unload);
|
||||||
assertTrue(failure.contains("ModdedIrisLog.error("));
|
assertTrue(failure.contains("ModdedIrisLog.error("));
|
||||||
assertTrue(failure.contains("throw "));
|
assertFalse(failure.contains("throw "));
|
||||||
|
|
||||||
String managerSource = source("ModdedDimensionManager.java");
|
String managerSource = source("ModdedDimensionManager.java");
|
||||||
String remove = method(managerSource, "public static boolean remove(MinecraftServer server, String dimensionId, boolean wipeStorage)");
|
String remove = method(managerSource, "public static boolean remove(MinecraftServer server, String dimensionId, boolean wipeStorage)");
|
||||||
|
|||||||
+19
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+48
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -1,20 +1,34 @@
|
|||||||
package art.arcane.iris.modded.service;
|
package art.arcane.iris.modded.service;
|
||||||
|
|
||||||
|
import art.arcane.iris.spi.IrisLogging;
|
||||||
import art.arcane.iris.util.project.matter.TileWrapper;
|
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.MantleChunk;
|
||||||
import art.arcane.volmlib.util.mantle.runtime.MantleDataAdapter;
|
import art.arcane.volmlib.util.mantle.runtime.MantleDataAdapter;
|
||||||
import art.arcane.volmlib.util.mantle.runtime.MantleHooks;
|
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.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.junit.Test;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
|
||||||
import java.lang.reflect.Proxy;
|
import java.lang.reflect.Proxy;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
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.assertThrows;
|
||||||
import static org.junit.Assert.assertTrue;
|
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 {
|
public class ModdedChunkUpdateServiceTest {
|
||||||
@Test
|
@Test
|
||||||
@@ -63,6 +77,93 @@ public class ModdedChunkUpdateServiceTest {
|
|||||||
assertEquals(List.of("materialize"), chunk.operations());
|
assertEquals(List.of("materialize"), chunk.operations());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void failedUpdateForgetsOnlyTheUpdatesAlreadyApplied() {
|
||||||
|
ChestUpdateMantleChunk chunk = new ChestUpdateMantleChunk();
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, () ->
|
||||||
|
ModdedChunkUpdateService.applyQueuedUpdates(chunk, (Integer x, Integer yf, Integer z) -> {
|
||||||
|
if (x == 2) {
|
||||||
|
throw new IllegalStateException("update failure");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
assertFalse(chunk.deleted());
|
||||||
|
assertNull(chunk.slice.get(1, 5, 1));
|
||||||
|
assertNotNull(chunk.slice.get(2, 5, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void failedChunkIsReportedAndTheNextChunkStillRuns() {
|
||||||
|
AtomicInteger updatedChunks = new AtomicInteger();
|
||||||
|
|
||||||
|
try (MockedStatic<IrisLogging> logging = mockStatic(IrisLogging.class)) {
|
||||||
|
logging.when(() -> IrisLogging.errorOnce(anyString(), anyString(), any(Object[].class))).thenReturn(true);
|
||||||
|
|
||||||
|
ModdedChunkUpdateService.isolateChunkFailure(
|
||||||
|
() -> {
|
||||||
|
throw new IllegalStateException("chunk failure");
|
||||||
|
},
|
||||||
|
() -> false, "example:updates", 0, 0);
|
||||||
|
ModdedChunkUpdateService.isolateChunkFailure(
|
||||||
|
updatedChunks::incrementAndGet, () -> false, "example:updates", 4, 0);
|
||||||
|
|
||||||
|
assertEquals(1, updatedChunks.get());
|
||||||
|
logging.verify(() -> IrisLogging.errorOnce(anyString(), anyString(), any(Object[].class)));
|
||||||
|
logging.verify(() -> IrisLogging.reportError(any(Throwable.class)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void endedPassRethrowsTheChunkFailure() {
|
||||||
|
IllegalStateException failure = new IllegalStateException("chunk failure");
|
||||||
|
|
||||||
|
IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
|
||||||
|
ModdedChunkUpdateService.isolateChunkFailure(
|
||||||
|
() -> {
|
||||||
|
throw failure;
|
||||||
|
},
|
||||||
|
() -> true, "example:updates", 0, 0));
|
||||||
|
|
||||||
|
assertSame(failure, thrown);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class ChestUpdateMantleChunk extends MantleChunk<Matter> {
|
||||||
|
private final Matter section = new IrisMatter(16, 16, 16);
|
||||||
|
private final MatterSlice<MatterUpdate> slice = section.slice(MatterUpdate.class);
|
||||||
|
private boolean deleted;
|
||||||
|
|
||||||
|
private ChestUpdateMantleChunk() {
|
||||||
|
super(1, 0, 0, emptyAdapter(), MantleHooks.NONE);
|
||||||
|
slice.set(1, 5, 1, UpdateMatter.ON);
|
||||||
|
slice.set(2, 5, 2, UpdateMatter.ON);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Matter get(int index) {
|
||||||
|
return section;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> void iterate(Class<T> type, Consumer4<Integer, Integer, Integer, T> iterator) {
|
||||||
|
if (type == MatterUpdate.class) {
|
||||||
|
iterator.accept(1, 5, 1, type.cast(UpdateMatter.ON));
|
||||||
|
iterator.accept(2, 5, 2, type.cast(UpdateMatter.ON));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteSlices(Class<?> type) {
|
||||||
|
if (type == MatterUpdate.class) {
|
||||||
|
deleted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean deleted() {
|
||||||
|
return deleted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static final class RecordingMantleChunk extends MantleChunk<Matter> {
|
private static final class RecordingMantleChunk extends MantleChunk<Matter> {
|
||||||
private final ArrayList<String> operations = new ArrayList<>();
|
private final ArrayList<String> operations = new ArrayList<>();
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import net.neoforged.neoforge.event.level.block.BreakBlockEvent;
|
|||||||
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
|
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
|
||||||
import net.neoforged.neoforge.event.server.ServerStartedEvent;
|
import net.neoforged.neoforge.event.server.ServerStartedEvent;
|
||||||
import net.neoforged.neoforge.event.server.ServerStartingEvent;
|
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.server.ServerStoppingEvent;
|
||||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||||
import net.neoforged.neoforge.registries.DeferredRegister;
|
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((ServerStartingEvent event) -> ModdedEngineBootstrap.start(event.getServer()));
|
||||||
NeoForge.EVENT_BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
|
NeoForge.EVENT_BUS.addListener((ServerStartedEvent event) -> ModdedEngineBootstrap.serverStarted(event.getServer()));
|
||||||
NeoForge.EVENT_BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
|
NeoForge.EVENT_BUS.addListener((ServerStoppingEvent event) -> ModdedEngineBootstrap.stop());
|
||||||
|
NeoForge.EVENT_BUS.addListener((ServerStoppedEvent event) -> ModdedEngineBootstrap.stopped());
|
||||||
NeoForge.EVENT_BUS.addListener((LevelEvent.Load event) -> {
|
NeoForge.EVENT_BUS.addListener((LevelEvent.Load event) -> {
|
||||||
if (event.getLevel() instanceof ServerLevel level) {
|
if (event.getLevel() instanceof ServerLevel level) {
|
||||||
ModdedEngineBootstrap.levelLoaded(level);
|
ModdedEngineBootstrap.levelLoaded(level);
|
||||||
|
|||||||
+87
-13
@@ -115,6 +115,7 @@ nmsBindings.each { key, value ->
|
|||||||
compileOnly(rootProject.libs.annotations)
|
compileOnly(rootProject.libs.annotations)
|
||||||
compileOnly(rootProject.libs.byteBuddy.core)
|
compileOnly(rootProject.libs.byteBuddy.core)
|
||||||
testImplementation('junit:junit:4.13.2')
|
testImplementation('junit:junit:4.13.2')
|
||||||
|
testImplementation('org.mockito:mockito-core:5.23.0')
|
||||||
testImplementation(project(':core'))
|
testImplementation(project(':core'))
|
||||||
testCompileOnly(volmLibCoordinate) {
|
testCompileOnly(volmLibCoordinate) {
|
||||||
transitive = false
|
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
|
// The three loader jars come out of nested standalone Gradle builds driven through Exec. The outer
|
||||||
// Gradle builds own the complete incremental model, so always launch them instead of allowing an
|
// task therefore has to carry the full inventory of what those builds read: every shared source tree,
|
||||||
// incomplete outer input inventory to publish stale jars.
|
// 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<File> resolveLocalVolmLibDirectory = { ->
|
Closure<File> resolveLocalVolmLibDirectory = { ->
|
||||||
String configured = localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()
|
String configured = localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()
|
||||||
? localVolmLibDirectory
|
? localVolmLibDirectory
|
||||||
@@ -324,25 +326,48 @@ List<Object> moddedSharedInputs = []
|
|||||||
'adapters/client-common/src',
|
'adapters/client-common/src',
|
||||||
'core/src/main',
|
'core/src/main',
|
||||||
'core/build.gradle',
|
'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/src/main',
|
||||||
'module/build.gradle.kts',
|
'module/build.gradle.kts',
|
||||||
'module/settings.gradle.kts',
|
'module/settings.gradle.kts',
|
||||||
|
'module/gradle.properties',
|
||||||
|
'module/lombok.config',
|
||||||
'module/builtin-modules.txt',
|
'module/builtin-modules.txt',
|
||||||
'spi/src/main',
|
'spi/src/main',
|
||||||
'spi/build.gradle',
|
'spi/build.gradle',
|
||||||
'build.gradle',
|
'build.gradle',
|
||||||
'settings.gradle',
|
'settings.gradle',
|
||||||
'gradle.properties',
|
'gradle.properties',
|
||||||
|
'lombok.config',
|
||||||
'gradle/libs.versions.toml',
|
'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) }
|
].each { String path -> moddedSharedInputs.add(layout.projectDirectory.file(path).asFile) }
|
||||||
File localVolmLibCheckout = useLocalVolmLib.equalsIgnoreCase('true') ? resolveLocalVolmLibDirectory() : null
|
File localVolmLibCheckout = useLocalVolmLib.equalsIgnoreCase('true') ? resolveLocalVolmLibDirectory() : null
|
||||||
if (localVolmLibCheckout != null) {
|
if (localVolmLibCheckout != null) {
|
||||||
moddedSharedInputs.add(new File(localVolmLibCheckout, 'shared/src/main'))
|
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<Void> rerunWhenVolmLibIsPublished = { Exec task ->
|
||||||
|
if (localVolmLibCheckout == null) {
|
||||||
|
task.outputs.upToDateWhen { false }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
Closure<Void> declareModdedJarIo = { Exec task, String adapter, String artifactName, Map<String, String> versions ->
|
Closure<Void> declareModdedJarIo = { Exec task, String adapter, String artifactName, Map<String, String> versions ->
|
||||||
task.inputs.files(moddedSharedInputs).withPropertyName('moddedSharedSources')
|
task.inputs.files(moddedSharedInputs).withPropertyName('moddedSharedSources')
|
||||||
|
.withPathSensitivity(PathSensitivity.RELATIVE)
|
||||||
task.inputs.files(
|
task.inputs.files(
|
||||||
layout.projectDirectory.file("adapters/${adapter}/src").asFile,
|
layout.projectDirectory.file("adapters/${adapter}/src").asFile,
|
||||||
layout.projectDirectory.file("adapters/${adapter}/build.gradle").asFile,
|
layout.projectDirectory.file("adapters/${adapter}/build.gradle").asFile,
|
||||||
@@ -351,10 +376,8 @@ Closure<Void> declareModdedJarIo = { Exec task, String adapter, String artifactN
|
|||||||
versions.each { String key, String value -> task.inputs.property(key, value) }
|
versions.each { String key, String value -> task.inputs.property(key, value) }
|
||||||
task.inputs.property('useLocalVolmLib', useLocalVolmLib)
|
task.inputs.property('useLocalVolmLib', useLocalVolmLib)
|
||||||
task.inputs.property('volmLibCoordinate', volmLibCoordinate)
|
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.file(layout.projectDirectory.file("adapters/${adapter}/build/libs/${artifactName}"))
|
||||||
task.outputs.upToDateWhen { false }
|
rerunWhenVolmLibIsPublished(task)
|
||||||
task.outputs.cacheIf { false }
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -372,8 +395,8 @@ tasks.register('fabricJar', Exec) {
|
|||||||
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
||||||
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
||||||
]
|
]
|
||||||
if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) {
|
if (localVolmLibCheckout != null) {
|
||||||
command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}")
|
environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath)
|
||||||
}
|
}
|
||||||
commandLine(command)
|
commandLine(command)
|
||||||
declareModdedJarIo(it, 'fabric', fabricArtifactName, [
|
declareModdedJarIo(it, 'fabric', fabricArtifactName, [
|
||||||
@@ -410,8 +433,8 @@ tasks.register('forgeJar', Exec) {
|
|||||||
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
||||||
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
||||||
]
|
]
|
||||||
if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) {
|
if (localVolmLibCheckout != null) {
|
||||||
command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}")
|
environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath)
|
||||||
}
|
}
|
||||||
commandLine(command)
|
commandLine(command)
|
||||||
declareModdedJarIo(it, 'forge', forgeArtifactName, [
|
declareModdedJarIo(it, 'forge', forgeArtifactName, [
|
||||||
@@ -448,8 +471,8 @@ tasks.register('neoforgeJar', Exec) {
|
|||||||
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
"-PuseLocalVolmLib=${useLocalVolmLib}",
|
||||||
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
"-PvolmLibCoordinate=${volmLibCoordinate}"
|
||||||
]
|
]
|
||||||
if (localVolmLibDirectory != null && !localVolmLibDirectory.isBlank()) {
|
if (localVolmLibCheckout != null) {
|
||||||
command.add("-PlocalVolmLibDirectory=${localVolmLibDirectory}")
|
environment('ORG_GRADLE_PROJECT_localVolmLibDirectory', localVolmLibCheckout.absolutePath)
|
||||||
}
|
}
|
||||||
commandLine(command)
|
commandLine(command)
|
||||||
declareModdedJarIo(it, 'neoforge', neoForgeArtifactName, [
|
declareModdedJarIo(it, 'neoforge', neoForgeArtifactName, [
|
||||||
@@ -486,6 +509,57 @@ tasks.named('neoforgeJar').configure {
|
|||||||
mustRunAfter(tasks.named('forgeJar'))
|
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<String> 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<String> commonModdedArtifactEntries = [
|
List<String> commonModdedArtifactEntries = [
|
||||||
'art/arcane/iris/engine/IrisEngine.class',
|
'art/arcane/iris/engine/IrisEngine.class',
|
||||||
'art/arcane/iris/spi/IrisPlatform.class',
|
'art/arcane/iris/spi/IrisPlatform.class',
|
||||||
|
|||||||
@@ -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 {
|
dependencies {
|
||||||
implementation(gradleApi())
|
implementation(gradleApi())
|
||||||
implementation('org.ow2.asm:asm:9.10.1')
|
implementation('org.ow2.asm:asm:9.10.1')
|
||||||
|
implementation('org.apache.commons:commons-compress:1.28.0')
|
||||||
implementation('com.github.VolmitSoftware:NMSTools:c88961416f')
|
implementation('com.github.VolmitSoftware:NMSTools:c88961416f')
|
||||||
implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21')
|
implementation('io.papermc.paperweight:paperweight-userdev:2.0.0-beta.21')
|
||||||
testImplementation('junit:junit:4.13.2')
|
testImplementation('junit:junit:4.13.2')
|
||||||
|
|||||||
@@ -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 org.gradle.api.GradleException;
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
|
||||||
import java.io.BufferedOutputStream;
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.nio.file.AtomicMoveNotSupportedException;
|
import java.nio.file.AtomicMoveNotSupportedException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
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.ZipEntry;
|
||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipFile;
|
||||||
import java.util.zip.ZipOutputStream;
|
|
||||||
|
|
||||||
public final class JarCompactor {
|
public final class JarCompactor {
|
||||||
private static final int BUFFER_BYTES = 64 * 1024;
|
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 {
|
private static void rewrite(Path source, Path destination) throws IOException {
|
||||||
byte[] buffer = new byte[BUFFER_BYTES];
|
byte[] buffer = new byte[BUFFER_BYTES];
|
||||||
try (InputStream rawInput = new BufferedInputStream(Files.newInputStream(source));
|
try (ZipFile input = new ZipFile(source.toFile());
|
||||||
ZipInputStream input = new ZipInputStream(rawInput);
|
ZipArchiveOutputStream output = new ZipArchiveOutputStream(destination)) {
|
||||||
OutputStream rawOutput = new BufferedOutputStream(Files.newOutputStream(destination));
|
if (!output.isSeekable()) {
|
||||||
ZipOutputStream output = new ZipOutputStream(rawOutput)) {
|
throw new IOException("Jar compaction requires seekable output.");
|
||||||
|
}
|
||||||
output.setLevel(9);
|
output.setLevel(9);
|
||||||
ZipEntry entry;
|
output.setUseZip64(Zip64Mode.Never);
|
||||||
while ((entry = input.getNextEntry()) != null) {
|
output.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NEVER);
|
||||||
|
Set<String> names = new HashSet<>();
|
||||||
|
Enumeration<? extends ZipEntry> entries = input.entries();
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
ZipEntry entry = entries.nextElement();
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
ZipEntry compacted = copyMetadata(entry);
|
if (!names.add(entry.getName())) {
|
||||||
output.putNextEntry(compacted);
|
throw new IOException("Duplicate jar entry: " + entry.getName());
|
||||||
int read;
|
|
||||||
while ((read = input.read(buffer)) >= 0) {
|
|
||||||
if (read > 0) {
|
|
||||||
output.write(buffer, 0, read);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
output.closeEntry();
|
output.putArchiveEntry(copyMetadata(entry));
|
||||||
|
copyEntry(input, output, entry, buffer);
|
||||||
|
output.closeArchiveEntry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ZipEntry copyMetadata(ZipEntry source) {
|
private static void copyEntry(ZipFile input, ZipArchiveOutputStream output, ZipEntry entry, byte[] buffer)
|
||||||
ZipEntry target = new ZipEntry(source.getName());
|
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);
|
target.setMethod(ZipEntry.DEFLATED);
|
||||||
if (source.getTime() >= 0L) {
|
if (source.getTime() >= 0L) {
|
||||||
target.setTime(source.getTime());
|
target.setTime(source.getTime());
|
||||||
@@ -78,7 +101,8 @@ public final class JarCompactor {
|
|||||||
target.setComment(source.getComment());
|
target.setComment(source.getComment());
|
||||||
}
|
}
|
||||||
if (source.getExtra() != null) {
|
if (source.getExtra() != null) {
|
||||||
target.setExtra(source.getExtra());
|
target.setExtraFields(ExtraFieldUtils.parse(source.getExtra(), true,
|
||||||
|
ZipArchiveEntry.ExtraFieldParsingMode.BEST_EFFORT));
|
||||||
}
|
}
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.rules.TemporaryFolder;
|
import org.junit.rules.TemporaryFolder;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileOutputStream;
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
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.JarEntry;
|
||||||
import java.util.jar.JarFile;
|
import java.util.jar.JarFile;
|
||||||
import java.util.jar.JarOutputStream;
|
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.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertNull;
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertThrows;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class JarCompactorTest {
|
public class JarCompactorTest {
|
||||||
@Rule
|
@Rule
|
||||||
@@ -36,4 +53,128 @@ public class JarCompactorTest {
|
|||||||
jar.getJarEntry("example/value.txt")).readAllBytes());
|
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<String, EntryIdentity> 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<ZipArchiveEntry> 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<String, EntryIdentity> identity(File artifact) throws Exception {
|
||||||
|
Map<String, EntryIdentity> entries = new TreeMap<>();
|
||||||
|
try (JarFile jar = new JarFile(artifact)) {
|
||||||
|
Enumeration<JarEntry> 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) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,6 @@ import lombok.NonNull;
|
|||||||
import org.bukkit.Bukkit;
|
import org.bukkit.Bukkit;
|
||||||
import org.bukkit.NamespacedKey;
|
import org.bukkit.NamespacedKey;
|
||||||
import org.bukkit.configuration.InvalidConfigurationException;
|
import org.bukkit.configuration.InvalidConfigurationException;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
|
||||||
import org.bukkit.configuration.file.YamlConfiguration;
|
import org.bukkit.configuration.file.YamlConfiguration;
|
||||||
import org.bukkit.entity.Player;
|
import org.bukkit.entity.Player;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
@@ -92,6 +91,9 @@ public class ServerConfigurator {
|
|||||||
private static final String COMPILER_INPUT_FINGERPRINT_CACHE = "datapack-compiler-input-fingerprint";
|
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; "
|
static final String POST_COMPILE_RESTART_WARNING = "Iris installed updated datapack registry entries; "
|
||||||
+ "restart the server before creating worlds or opening Studios.";
|
+ "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 final int FINGERPRINT_BUFFER_BYTES = 64 * 1024;
|
||||||
private static volatile boolean loadedDatapackRuntimeReady;
|
private static volatile boolean loadedDatapackRuntimeReady;
|
||||||
private static volatile String loadedDatapackCompilerInputFingerprint = "";
|
private static volatile String loadedDatapackCompilerInputFingerprint = "";
|
||||||
@@ -108,11 +110,27 @@ public class ServerConfigurator {
|
|||||||
}
|
}
|
||||||
IrisSettings.IrisSettingsAutoconfiguration s = IrisSettings.get().getAutoConfiguration();
|
IrisSettings.IrisSettingsAutoconfiguration s = IrisSettings.get().getAutoConfiguration();
|
||||||
if (s.isConfigureSpigotTimeoutTime()) {
|
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()) {
|
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()) {
|
if (DefaultPackBootstrapProvisioner.wasProvisionedThisStartup()) {
|
||||||
@@ -240,34 +258,45 @@ public class ServerConfigurator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static void increaseKeepAliveSpigot() throws IOException, InvalidConfigurationException {
|
private static void increaseKeepAliveSpigot() throws IOException, InvalidConfigurationException {
|
||||||
File spigotConfig = new File("spigot.yml");
|
increaseKeepAliveSpigot(SPIGOT_CONFIGURATION, timeoutConfiguration());
|
||||||
FileConfiguration f = new YamlConfiguration();
|
}
|
||||||
f.load(spigotConfig);
|
|
||||||
long tt = f.getLong("settings.timeout-time");
|
|
||||||
|
|
||||||
long spigotTimeout = TimeUnit.MINUTES.toSeconds(5);
|
static void increaseKeepAliveSpigot(Path file, ServerTimeoutConfiguration timeouts) throws IOException, InvalidConfigurationException {
|
||||||
|
long previous = loadConfiguration(file).getLong(ServerTimeoutConfiguration.SPIGOT_TIMEOUT_KEY);
|
||||||
if (tt < spigotTimeout) {
|
long minimum = TimeUnit.MINUTES.toSeconds(5);
|
||||||
IrisLogging.warn("Updating spigot.yml timeout-time: " + tt + " -> " + spigotTimeout + " (5 minutes)");
|
if (previous >= minimum) {
|
||||||
IrisLogging.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value.");
|
return;
|
||||||
f.set("settings.timeout-time", spigotTimeout);
|
|
||||||
f.save(spigotConfig);
|
|
||||||
}
|
}
|
||||||
|
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 {
|
private static void increasePaperWatchdog() throws IOException, InvalidConfigurationException {
|
||||||
File spigotConfig = new File("config/paper-global.yml");
|
increasePaperWatchdog(PAPER_GLOBAL_CONFIGURATION, timeoutConfiguration());
|
||||||
FileConfiguration f = new YamlConfiguration();
|
}
|
||||||
f.load(spigotConfig);
|
|
||||||
long tt = f.getLong("watchdog.early-warning-delay");
|
|
||||||
|
|
||||||
long watchdog = TimeUnit.MINUTES.toMillis(3);
|
static void increasePaperWatchdog(Path file, ServerTimeoutConfiguration timeouts) throws IOException, InvalidConfigurationException {
|
||||||
if (tt < watchdog) {
|
long previous = loadConfiguration(file).getLong(ServerTimeoutConfiguration.PAPER_WATCHDOG_KEY);
|
||||||
IrisLogging.warn("Updating paper.yml watchdog early-warning-delay: " + tt + " -> " + watchdog + " (3 minutes)");
|
long minimum = TimeUnit.MINUTES.toMillis(3);
|
||||||
IrisLogging.warn("You can disable this change (autoconfigureServer) in Iris settings, then change back the value.");
|
if (previous >= minimum) {
|
||||||
f.set("watchdog.early-warning-delay", watchdog);
|
return;
|
||||||
f.save(spigotConfig);
|
|
||||||
}
|
}
|
||||||
|
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<File> getDatapacksFolder() {
|
public static KList<File> getDatapacksFolder() {
|
||||||
@@ -852,7 +881,7 @@ public class ServerConfigurator {
|
|||||||
|
|
||||||
private static void writeFingerprintCache(Path cacheFile, PackFingerprint fingerprint) {
|
private static void writeFingerprintCache(Path cacheFile, PackFingerprint fingerprint) {
|
||||||
try {
|
try {
|
||||||
writeFingerprintAtomic(cacheFile, fingerprint.content() + "\n" + fingerprint.metadata());
|
writeStringAtomic(cacheFile, fingerprint.content() + "\n" + fingerprint.metadata());
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
IrisLogging.warn("Failed to write datapack fingerprint cache: " + e.getMessage());
|
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) {
|
private static void writeCompilerInputFingerprintCache(Path cacheFile, String fingerprint) {
|
||||||
try {
|
try {
|
||||||
writeFingerprintAtomic(cacheFile, fingerprint);
|
writeStringAtomic(cacheFile, fingerprint);
|
||||||
} catch (IOException exception) {
|
} catch (IOException exception) {
|
||||||
IrisLogging.warn("Failed to write datapack compiler-input fingerprint cache: "
|
IrisLogging.warn("Failed to write datapack compiler-input fingerprint cache: "
|
||||||
+ exception.getMessage());
|
+ 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 absoluteTarget = target.toAbsolutePath().normalize();
|
||||||
Path parent = absoluteTarget.getParent();
|
Path parent = absoluteTarget.getParent();
|
||||||
if (parent == null) {
|
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);
|
Files.createDirectories(parent);
|
||||||
Path staged = Files.createTempFile(parent, ".datapack-fingerprint-", ".tmp");
|
Path staged = Files.createTempFile(parent, ".iris-write-", ".tmp");
|
||||||
try {
|
try {
|
||||||
Files.writeString(staged, fingerprint, StandardCharsets.UTF_8);
|
Files.writeString(staged, content, StandardCharsets.UTF_8);
|
||||||
try (FileChannel channel = FileChannel.open(staged, StandardOpenOption.WRITE)) {
|
try (FileChannel channel = FileChannel.open(staged, StandardOpenOption.WRITE)) {
|
||||||
channel.force(true);
|
channel.force(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<SavedTimeout> 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<SavedTimeout> 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<SavedTimeout> 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<SavedTimeout> changes) throws IOException {
|
||||||
|
ServerConfigurator.writeStringAtomic(recoveryFile, JSON.toJson(new SavedTimeouts(changes)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SavedTimeout find(List<SavedTimeout> 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<SavedTimeout> changes) {
|
||||||
|
private SavedTimeouts {
|
||||||
|
changes = List.copyOf(changes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -152,15 +152,19 @@ public final class IrisWorldRemovalService {
|
|||||||
boolean deleteFiles,
|
boolean deleteFiles,
|
||||||
AtomicBoolean terminal
|
AtomicBoolean terminal
|
||||||
) {
|
) {
|
||||||
|
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
|
||||||
CompletableFuture<RemovalResult> operation = phase(
|
CompletableFuture<RemovalResult> operation = phase(
|
||||||
RemovalStatus.RESOLUTION_FAILED,
|
RemovalStatus.TELEPORT_FAILED,
|
||||||
() -> backend.beginMaintenance(resolved).thenApply(ignored -> resolved),
|
() -> backend.evacuatePlayers(resolved).thenApply(ignored -> resolved),
|
||||||
terminal
|
terminal
|
||||||
)
|
)
|
||||||
.thenCompose(activeWorld -> phase(
|
.thenCompose(activeWorld -> phase(
|
||||||
RemovalStatus.TELEPORT_FAILED,
|
RemovalStatus.RESOLUTION_FAILED,
|
||||||
() -> backend.evacuatePlayers(activeWorld)
|
() -> {
|
||||||
.thenApply(ignored -> activeWorld),
|
CompletableFuture<Void> begun = backend.beginMaintenance(activeWorld);
|
||||||
|
maintenanceEntered.set(true);
|
||||||
|
return begun.thenApply(ignored -> activeWorld);
|
||||||
|
},
|
||||||
terminal
|
terminal
|
||||||
))
|
))
|
||||||
.thenCompose(activeWorld -> phase(
|
.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) -> {
|
.handle((ignored, cleanupFailure) -> {
|
||||||
if (cleanupFailure != null) {
|
if (cleanupFailure != null) {
|
||||||
Throwable unwrappedCleanup = unwrap(cleanupFailure);
|
Throwable unwrappedCleanup = unwrap(cleanupFailure);
|
||||||
@@ -216,6 +220,10 @@ public final class IrisWorldRemovalService {
|
|||||||
})).thenCompose(result -> result);
|
})).thenCompose(result -> result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private CompletableFuture<Void> endMaintenance(ResolvedWorld resolved, boolean entered) {
|
||||||
|
return entered ? backend.endMaintenance(resolved) : CompletableFuture.completedFuture(null);
|
||||||
|
}
|
||||||
|
|
||||||
private CompletableFuture<ResolvedWorld> validateResolvedWorld(ResolvedWorld resolvedWorld) {
|
private CompletableFuture<ResolvedWorld> validateResolvedWorld(ResolvedWorld resolvedWorld) {
|
||||||
if (!resolvedWorld.managed()) {
|
if (!resolvedWorld.managed()) {
|
||||||
return CompletableFuture.failedFuture(new RemovalFailure(
|
return CompletableFuture.failedFuture(new RemovalFailure(
|
||||||
|
|||||||
@@ -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_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_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_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_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_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");
|
public static final TextKey IRIS_MODDED_COMMANDS_EVACUATED_PLAYER_S_FROM = text("iris.modded.irismoddedcommands.evacuated_player_s_from");
|
||||||
|
|||||||
@@ -230,6 +230,9 @@ public interface INMSBinding {
|
|||||||
default void flushChunkIO(World world) {
|
default void flushChunkIO(World world) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
default void reconcileNativeStructurePois(Chunk chunk) {
|
||||||
|
}
|
||||||
|
|
||||||
void injectBiomesFromMantle(Chunk e, Mantle<Matter> mantle);
|
void injectBiomesFromMantle(Chunk e, Mantle<Matter> mantle);
|
||||||
|
|
||||||
ItemStack applyCustomNbt(ItemStack itemStack, KMap<String, Object> customNbt) throws IllegalArgumentException;
|
ItemStack applyCustomNbt(ItemStack itemStack, KMap<String, Object> customNbt) throws IllegalArgumentException;
|
||||||
|
|||||||
@@ -485,12 +485,17 @@ public final class StudioOpenCoordinator {
|
|||||||
AtomicBoolean unloadStarted = new AtomicBoolean(false);
|
AtomicBoolean unloadStarted = new AtomicBoolean(false);
|
||||||
AtomicBoolean folderDeleted = new AtomicBoolean(!deleteFolder);
|
AtomicBoolean folderDeleted = new AtomicBoolean(!deleteFolder);
|
||||||
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
||||||
if (world != null) {
|
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
|
||||||
IrisToolbelt.beginWorldMaintenance(world, "studio-close", true);
|
|
||||||
}
|
|
||||||
|
|
||||||
CompletableFuture<Void> sequence = sequenceStudioClose(
|
CompletableFuture<Void> sequence = sequenceStudioClose(
|
||||||
() -> evacuateWorldFamily(worldName, world),
|
() -> evacuateWorldFamily(worldName, world),
|
||||||
|
() -> {
|
||||||
|
if (world == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
IrisToolbelt.beginWorldMaintenance(world, "studio-close", true);
|
||||||
|
maintenanceEntered.set(true);
|
||||||
|
},
|
||||||
() -> {
|
() -> {
|
||||||
unloadStarted.set(true);
|
unloadStarted.set(true);
|
||||||
return unloadWorldFamily(worldName, world).thenRun(() -> {
|
return unloadWorldFamily(worldName, world).thenRun(() -> {
|
||||||
@@ -535,7 +540,7 @@ public final class StudioOpenCoordinator {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
return operation.whenComplete((result, throwable) -> {
|
return operation.whenComplete((result, throwable) -> {
|
||||||
if (world != null) {
|
if (maintenanceEntered.get()) {
|
||||||
IrisToolbelt.endWorldMaintenance(world, "studio-close", true);
|
IrisToolbelt.endWorldMaintenance(world, "studio-close", true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -549,22 +554,27 @@ public final class StudioOpenCoordinator {
|
|||||||
|
|
||||||
static CompletableFuture<Void> sequenceStudioClose(
|
static CompletableFuture<Void> sequenceStudioClose(
|
||||||
Supplier<CompletableFuture<Void>> evacuate,
|
Supplier<CompletableFuture<Void>> evacuate,
|
||||||
|
Runnable enterMaintenance,
|
||||||
Supplier<CompletableFuture<Void>> unload,
|
Supplier<CompletableFuture<Void>> unload,
|
||||||
Supplier<CompletableFuture<Void>> closeGenerator,
|
Supplier<CompletableFuture<Void>> closeGenerator,
|
||||||
Supplier<CompletableFuture<Void>> deleteFolders
|
Supplier<CompletableFuture<Void>> deleteFolders
|
||||||
) {
|
) {
|
||||||
return sequenceStudioClose(evacuate, unload, closeGenerator, deleteFolders, () -> false);
|
return sequenceStudioClose(evacuate, enterMaintenance, unload, closeGenerator, deleteFolders, () -> false);
|
||||||
}
|
}
|
||||||
|
|
||||||
static CompletableFuture<Void> sequenceStudioClose(
|
static CompletableFuture<Void> sequenceStudioClose(
|
||||||
Supplier<CompletableFuture<Void>> evacuate,
|
Supplier<CompletableFuture<Void>> evacuate,
|
||||||
|
Runnable enterMaintenance,
|
||||||
Supplier<CompletableFuture<Void>> unload,
|
Supplier<CompletableFuture<Void>> unload,
|
||||||
Supplier<CompletableFuture<Void>> closeGenerator,
|
Supplier<CompletableFuture<Void>> closeGenerator,
|
||||||
Supplier<CompletableFuture<Void>> deleteFolders,
|
Supplier<CompletableFuture<Void>> deleteFolders,
|
||||||
BooleanSupplier terminalTimeout
|
BooleanSupplier terminalTimeout
|
||||||
) {
|
) {
|
||||||
return invokePhase(evacuate)
|
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(closeGenerator, terminalTimeout))
|
||||||
.thenCompose(ignored -> invokePhaseUnlessTimedOut(deleteFolders, terminalTimeout));
|
.thenCompose(ignored -> invokePhaseUnlessTimedOut(deleteFolders, terminalTimeout));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -845,12 +845,12 @@ public class StudioSVC implements IrisService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void destroyStudioWorld(World world, PlatformChunkGenerator generator) {
|
private void destroyStudioWorld(World world, PlatformChunkGenerator generator) {
|
||||||
IrisToolbelt.beginWorldMaintenance(world, "studio-disable", true);
|
|
||||||
try {
|
try {
|
||||||
IrisToolbelt.evacuate(world);
|
IrisToolbelt.evacuate(world);
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
IrisLogging.reportError("Failed to evacuate studio world \"" + world.getName() + "\" during shutdown cleanup.", e);
|
IrisLogging.reportError("Failed to evacuate studio world \"" + world.getName() + "\" during shutdown cleanup.", e);
|
||||||
}
|
}
|
||||||
|
IrisToolbelt.beginWorldMaintenance(world, "studio-disable", true);
|
||||||
try {
|
try {
|
||||||
WorldLifecycleService.get().unloadAsync(world, false)
|
WorldLifecycleService.get().unloadAsync(world, false)
|
||||||
.thenCompose(unloaded -> {
|
.thenCompose(unloaded -> {
|
||||||
|
|||||||
@@ -313,6 +313,8 @@ public class IrisCreator {
|
|||||||
.thenCompose(Function.identity())
|
.thenCompose(Function.identity())
|
||||||
.get(WORLD_CREATE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
.get(WORLD_CREATE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
if (!studio && !benchmark) {
|
if (!studio && !benchmark) {
|
||||||
|
World createdWorld = world;
|
||||||
|
J.sfut(() -> createdWorld.save()).get(WORLD_CREATE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
awaitInitialSpawnPreparation(access, name);
|
awaitInitialSpawnPreparation(access, name);
|
||||||
}
|
}
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
@@ -745,12 +747,15 @@ public class IrisCreator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (activeWorld != null) {
|
if (activeWorld != null) {
|
||||||
IrisToolbelt.beginWorldMaintenance(activeWorld, "world-create-rollback", true);
|
boolean maintenanceEntered = false;
|
||||||
try {
|
try {
|
||||||
PlatformChunkGenerator generator = IrisToolbelt.access(activeWorld);
|
PlatformChunkGenerator generator = IrisToolbelt.access(activeWorld);
|
||||||
boolean evacuated = Boolean.TRUE.equals(IrisToolbelt.evacuateAsync(activeWorld)
|
boolean evacuated = Boolean.TRUE.equals(IrisToolbelt.evacuateAsync(activeWorld)
|
||||||
.get(ROLLBACK_PHASE_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
.get(ROLLBACK_PHASE_TIMEOUT_SECONDS, TimeUnit.SECONDS));
|
||||||
if (!evacuated) {
|
if (evacuated) {
|
||||||
|
IrisToolbelt.beginWorldMaintenance(activeWorld, "world-create-rollback", true);
|
||||||
|
maintenanceEntered = true;
|
||||||
|
} else {
|
||||||
safeToDelete = false;
|
safeToDelete = false;
|
||||||
failure.addSuppressed(new IllegalStateException(
|
failure.addSuppressed(new IllegalStateException(
|
||||||
"Rollback could not evacuate world \"" + name + "\"."));
|
"Rollback could not evacuate world \"" + name + "\"."));
|
||||||
@@ -778,7 +783,9 @@ public class IrisCreator {
|
|||||||
ServerConfigurator.restart("World creation rollback timed out for \"" + name + "\".");
|
ServerConfigurator.restart("World creation rollback timed out for \"" + name + "\".");
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
IrisToolbelt.endWorldMaintenance(activeWorld, "world-create-rollback", true);
|
if (maintenanceEntered) {
|
||||||
|
IrisToolbelt.endWorldMaintenance(activeWorld, "world-create-rollback", true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ package art.arcane.iris.engine;
|
|||||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||||
import art.arcane.iris.core.IrisSettings;
|
import art.arcane.iris.core.IrisSettings;
|
||||||
import art.arcane.volmlib.util.cache.CacheKey;
|
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.Engine;
|
||||||
import art.arcane.iris.engine.framework.EngineAssignedWorldManager;
|
import art.arcane.iris.engine.framework.EngineAssignedWorldManager;
|
||||||
import art.arcane.iris.spi.IrisLogging;
|
import art.arcane.iris.spi.IrisLogging;
|
||||||
@@ -205,6 +206,8 @@ public class IrisWorldManager extends EngineAssignedWorldManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
INMS.get().reconcileNativeStructurePois(e);
|
||||||
|
|
||||||
if (cleanupServiceStopped || cleanupService == null || cleanupService.isShutdown()) {
|
if (cleanupServiceStopped || cleanupService == null || cleanupService.isShutdown()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,43 +19,33 @@
|
|||||||
package art.arcane.iris.platform.bukkit;
|
package art.arcane.iris.platform.bukkit;
|
||||||
|
|
||||||
import art.arcane.iris.spi.PlatformBiome;
|
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 org.bukkit.block.Biome;
|
||||||
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Interned Bukkit adapter for a neutral biome handle.
|
* Interned Bukkit adapter for a neutral biome handle.
|
||||||
*/
|
*/
|
||||||
public final class BukkitBiome implements PlatformBiome {
|
public final class BukkitBiome implements PlatformBiome {
|
||||||
private static final ConcurrentHashMap<String, BukkitBiome> CACHE = new ConcurrentHashMap<>();
|
private static final Cache<Biome, BukkitBiome> CACHE = Caffeine.newBuilder()
|
||||||
|
.weakKeys()
|
||||||
|
.maximumSize(4_096)
|
||||||
|
.build();
|
||||||
|
|
||||||
private final Biome biome;
|
private final Biome biome;
|
||||||
private final String key;
|
private final String key;
|
||||||
private final String namespace;
|
private final String namespace;
|
||||||
|
|
||||||
private BukkitBiome(Biome biome, String key) {
|
private BukkitBiome(Biome biome) {
|
||||||
this.biome = biome;
|
this.biome = biome;
|
||||||
this.key = key;
|
NamespacedKey biomeKey = biome.getKey();
|
||||||
int colon = key.indexOf(':');
|
this.key = biomeKey.toString();
|
||||||
this.namespace = colon >= 0 ? key.substring(0, colon) : "minecraft";
|
this.namespace = biomeKey.getNamespace();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static BukkitBiome of(Biome biome) {
|
public static BukkitBiome of(Biome biome) {
|
||||||
String key = biomeKey(biome);
|
return CACHE.get(biome, BukkitBiome::new);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Die Konsole muss einen Spieler benennen: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Die Konsole muss einen Spieler benennen: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} wird nicht von Iris generiert.",
|
"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.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.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.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.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} Spieler von {value} nach {value2} evakuiert.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La consola debe indicar un jugador: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La consola debe indicar un jugador: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} no se genera por Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Se evacuaron {count} jugador(es) de {value} a {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolin on nimettävä pelaaja: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolin on nimettävä pelaaja: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} ei ole tuotettu Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuoitu {count} pelaajat {value} - {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console doit indiquer un joueur : /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console doit indiquer un joueur : /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} n'est pas généré par Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} joueur(s) évacué(s) de {value} vers {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "הקונסולה חייבת לקרוא לשחקן: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "הקונסולה חייבת לקרוא לשחקן: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} לא נוצר על ידי Iris.",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} לא נוצר על ידי Iris.",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "טלפורט נכשל: ממד {dimensionId} לא טעון.",
|
"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.is_not_generated_by_iris_2": "{value} לא נוצר על ידי Iris.",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "לא ניתן לפנות לעולם הראשי, אין מקום לשלוח שחקנים.",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "לא ניתן לפנות לעולם הראשי, אין מקום לשלוח שחקנים.",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "הערכה {count} שחקן(s) {value} כדי {value2}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "הערכה {count} שחקן(s) {value} כדי {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console deve specificare un giocatore: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "La console deve specificare un giocatore: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} non è generato da Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuati {count} giocatori da {value} a {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "コンソールではプレイヤーを指定してください: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "コンソールではプレイヤーを指定してください: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} は Iris によって生成されていません。",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} は Iris によって生成されていません。",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "テレポートに失敗しました: ディメンション {dimensionId} は読み込まれていません。",
|
"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.is_not_generated_by_iris_2": "{value} は Iris によって生成されていません。",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "プライマリーワールドからは退避できません。プレイヤーの移動先がありません。",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "プライマリーワールドからは退避できません。プレイヤーの移動先がありません。",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} 人のプレイヤーを {value} から {value2} へ退避させました。",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "{count} 人のプレイヤーを {value} から {value2} へ退避させました。",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "콘솔은 플레이어를 지정해야 합니다: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "콘솔은 플레이어를 지정해야 합니다: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 에 의해 생성되지 않음 Iris.",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 에 의해 생성되지 않음 Iris.",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 실패: 차원 {dimensionId} 로드 되지 않습니다.",
|
"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.is_not_generated_by_iris_2": "{value} 에 의해 생성되지 않음 Iris.",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "1 차 세계를 피할 수 없습니다. 플레이어에게 보내는 곳이 없습니다.",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "1 차 세계를 피할 수 없습니다. 플레이어에게 보내는 곳이 없습니다.",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "플레이어 {count}명을 {value}에서 {value2}(으)로 대피시켰습니다.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "플레이어 {count}명을 {value}에서 {value2}(으)로 대피시켰습니다.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolė turi pavadinti žaidėją: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsolė turi pavadinti žaidėją: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} generuoja ne Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuoti {count} grotuvas (-ai) iš {value} iki {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console moet een speler een naam geven: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console moet een speler een naam geven: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} wordt niet gegenereerd door Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Ontruimd {count} speler(s) van {value} tot {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsola musi nazwać gracza: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsola musi nazwać gracza: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} nie jest generowany przez Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Ewakuowane {count} odtwarzacz (-i) z {value} do {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "A consola deve nomear um jogador: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "A consola deve nomear um jogador: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} não é gerado por Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuado {count} jogador( s) de {value} para {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Консоль должна называть игрока: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Консоль должна называть игрока: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} не генерируется путем Iris.",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} не генерируется путем Iris.",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Телепорт провалился: измерение {dimensionId} не загружается.",
|
"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.is_not_generated_by_iris_2": "{value} не генерируется путем Iris.",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Нельзя эвакуировать основной мир, негде отправить игроков.",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "Нельзя эвакуировать основной мир, негде отправить игроков.",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "эвакуированный {count} Игрок(ы) из {value} то {value2}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "эвакуированный {count} Игрок(ы) из {value} то {value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsol bir oyuncu adı olmalıdır: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Konsol bir oyuncu adı olmalıdır: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} tarafından üretilmiyor Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evakuated {count} oyuncu(s) -den {value} tom için {value2}.",
|
||||||
|
|||||||
@@ -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 <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Cần phải đặt tên người chơi: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} không được tạo ra bởi Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Đã sơ tán{count}người chơi từ{value}phải{value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制台必须给玩家命名 : /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制台必须给玩家命名 : /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 失败: 维度 {dimensionId} 未加载。",
|
"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.is_not_generated_by_iris_2": "{value} 不由 Iris.",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "无法撤离主世界; 没有地方可以发送玩家 。",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "无法撤离主世界; 没有地方可以发送玩家 。",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤离{count}玩家从{value}改为:{value2}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤离{count}玩家从{value}改为:{value2}.",
|
||||||
|
|||||||
@@ -307,7 +307,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制檯必須給玩家命名 : /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "控制檯必須給玩家命名 : /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.",
|
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} 不由 Iris.",
|
||||||
"iris.modded.irismoddedcommands.teleport_failed_dimension_is_not_loaded": "Teleport 失敗: 維度 {dimensionId} 未載入。",
|
"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.is_not_generated_by_iris_2": "{value} 不由 Iris.",
|
||||||
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "無法撤離主世界; 沒有地方可以傳送玩家 。",
|
"iris.modded.irismoddedcommands.cannot_evacuate_primary_world_there_is_nowhere_send_players": "無法撤離主世界; 沒有地方可以傳送玩家 。",
|
||||||
"iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤離{count}玩家從{value}改為:{value2}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "已撤離{count}玩家從{value}改為:{value2}.",
|
||||||
|
|||||||
@@ -284,7 +284,10 @@
|
|||||||
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console must name a player: /iris tp <dimension> <player>",
|
"iris.modded.irismoddedcommands.console_must_name_player_iris_tp_dimension_player": "Console must name a player: /iris tp <dimension> <player>",
|
||||||
"iris.modded.irismoddedcommands.is_not_generated_by_iris": "{value} is not generated by Iris.",
|
"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.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.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.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}.",
|
"iris.modded.irismoddedcommands.evacuated_player_s_from": "Evacuated {count} player(s) from {value} to {value2}.",
|
||||||
|
|||||||
@@ -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<IrisLogging> 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<IrisLogging> 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<IrisLogging> 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<IrisLogging> 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<IrisLogging> 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<IrisLogging> 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<ServerConfigurator> 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<IrisLogging> logging = mockStatic(IrisLogging.class)) {
|
||||||
|
ServerConfigurator.increaseKeepAliveSpigot(file, timeouts());
|
||||||
|
try (MockedStatic<ServerConfigurator> 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<IrisLogging> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -67,12 +67,26 @@ public class IrisWorldRemovalServiceTest {
|
|||||||
assertTrue(result.succeeded());
|
assertTrue(result.succeeded());
|
||||||
assertTrue(result.registryChanged());
|
assertTrue(result.registryChanged());
|
||||||
assertEquals(
|
assertEquals(
|
||||||
List.of("resolve", "begin", "evacuate", "unload", "close", "unregister", "unregisterRegistry", "end"),
|
List.of("resolve", "evacuate", "begin", "unload", "close", "unregister", "unregisterRegistry", "end"),
|
||||||
backend.operations
|
backend.operations
|
||||||
);
|
);
|
||||||
assertTrue(coordinator.isIdle());
|
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
|
@Test
|
||||||
public void configurationFailureStopsBeforeDeletionAndRetainsCause() throws Exception {
|
public void configurationFailureStopsBeforeDeletionAndRetainsCause() throws Exception {
|
||||||
LifecycleOperationCoordinator coordinator = new LifecycleOperationCoordinator();
|
LifecycleOperationCoordinator coordinator = new LifecycleOperationCoordinator();
|
||||||
|
|||||||
+32
-4
@@ -22,12 +22,37 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
|
|
||||||
StudioOpenCoordinator.sequenceStudioClose(
|
StudioOpenCoordinator.sequenceStudioClose(
|
||||||
() -> phase(phases, "evacuate"),
|
() -> phase(phases, "evacuate"),
|
||||||
|
() -> phases.add("maintenance"),
|
||||||
() -> phase(phases, "unload"),
|
() -> phase(phases, "unload"),
|
||||||
() -> phase(phases, "close-generator"),
|
() -> phase(phases, "close-generator"),
|
||||||
() -> phase(phases, "delete-folders")
|
() -> phase(phases, "delete-folders")
|
||||||
).join();
|
).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<String> 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
|
@Test
|
||||||
@@ -38,6 +63,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
try {
|
try {
|
||||||
StudioOpenCoordinator.sequenceStudioClose(
|
StudioOpenCoordinator.sequenceStudioClose(
|
||||||
() -> phase(phases, "evacuate"),
|
() -> phase(phases, "evacuate"),
|
||||||
|
() -> phases.add("maintenance"),
|
||||||
() -> {
|
() -> {
|
||||||
phases.add("unload");
|
phases.add("unload");
|
||||||
return CompletableFuture.failedFuture(failure);
|
return CompletableFuture.failedFuture(failure);
|
||||||
@@ -50,7 +76,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
assertSame(failure, exception.getCause());
|
assertSame(failure, exception.getCause());
|
||||||
}
|
}
|
||||||
|
|
||||||
assertEquals(List.of("evacuate", "unload"), phases);
|
assertEquals(List.of("evacuate", "maintenance", "unload"), phases);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -61,6 +87,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
try {
|
try {
|
||||||
StudioOpenCoordinator.sequenceStudioClose(
|
StudioOpenCoordinator.sequenceStudioClose(
|
||||||
() -> phase(phases, "evacuate"),
|
() -> phase(phases, "evacuate"),
|
||||||
|
() -> phases.add("maintenance"),
|
||||||
() -> phase(phases, "unload"),
|
() -> phase(phases, "unload"),
|
||||||
() -> {
|
() -> {
|
||||||
phases.add("close-generator");
|
phases.add("close-generator");
|
||||||
@@ -73,7 +100,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
assertSame(failure, exception.getCause());
|
assertSame(failure, exception.getCause());
|
||||||
}
|
}
|
||||||
|
|
||||||
assertEquals(List.of("evacuate", "unload", "close-generator"), phases);
|
assertEquals(List.of("evacuate", "maintenance", "unload", "close-generator"), phases);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -84,6 +111,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
|
|
||||||
CompletableFuture<Void> close = StudioOpenCoordinator.sequenceStudioClose(
|
CompletableFuture<Void> close = StudioOpenCoordinator.sequenceStudioClose(
|
||||||
() -> phase(phases, "evacuate"),
|
() -> phase(phases, "evacuate"),
|
||||||
|
() -> phases.add("maintenance"),
|
||||||
() -> {
|
() -> {
|
||||||
phases.add("unload");
|
phases.add("unload");
|
||||||
return unload;
|
return unload;
|
||||||
@@ -100,7 +128,7 @@ public class StudioOpenCoordinatorCloseSequenceTest {
|
|||||||
} catch (CompletionException exception) {
|
} catch (CompletionException exception) {
|
||||||
assertEquals("Studio close stopped after its terminal timeout.", exception.getCause().getMessage());
|
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
|
@Test
|
||||||
|
|||||||
@@ -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<INMS> 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<INMS> nms = mockStatic(INMS.class)) {
|
||||||
|
nms.when(INMS::get).thenReturn(binding);
|
||||||
|
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||||
|
() -> manager.onChunkLoad(chunk, true)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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("<clinit>") ? 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user