mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-30 01:34:04 +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
|
||||
public boolean clearChunkBlocks(Chunk bukkitChunk) {
|
||||
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.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.WorldGenRegion;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.Mth;
|
||||
@@ -60,6 +61,7 @@ import java.util.function.Supplier;
|
||||
|
||||
final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
private static final int WRITE_RADIUS = 1;
|
||||
private static final NativeStructurePoiUpdates POI_UPDATES = NativeStructurePoiUpdates.create();
|
||||
|
||||
private final WorldGenLevel delegate;
|
||||
private final ChunkPos generationCenter;
|
||||
@@ -426,23 +428,45 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
|
||||
@Override
|
||||
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
|
||||
return recordWrite(position, isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit));
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
return recordWrite(position, POI_UPDATES != null
|
||||
? POI_UPDATES.setBlock(delegate, position, state, updateFlags, updateLimit)
|
||||
: delegate.setBlock(position, state, updateFlags, updateLimit));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeBlock(BlockPos position, boolean move) {
|
||||
return recordWrite(position, isWritable(position) && delegate.removeBlock(position, move));
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
if (reconcilesPoiThroughSetBlock()) {
|
||||
return setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, Block.UPDATE_LIMIT);
|
||||
}
|
||||
return recordWrite(position, delegate.removeBlock(position, move));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
|
||||
return recordWrite(position, isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit));
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
if (reconcilesPoiThroughSetBlock()) {
|
||||
return !delegate.getBlockState(position).isAir()
|
||||
&& setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, updateLimit);
|
||||
}
|
||||
return recordWrite(position, delegate.destroyBlock(position, drop, source, updateLimit));
|
||||
}
|
||||
|
||||
WrittenBlocks writtenBlocks() {
|
||||
return writtenBlocks;
|
||||
}
|
||||
|
||||
private boolean reconcilesPoiThroughSetBlock() {
|
||||
return POI_UPDATES != null && delegate instanceof WorldGenRegion;
|
||||
}
|
||||
|
||||
private boolean recordWrite(BlockPos position, boolean written) {
|
||||
if (written) {
|
||||
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
|
||||
|
||||
+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.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.link.MultiverseCoreLink;
|
||||
import art.arcane.iris.core.agent.AttachSignal;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.gui.BukkitGuiHost;
|
||||
import art.arcane.iris.core.gui.PregeneratorJob;
|
||||
@@ -203,7 +204,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
private final PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this);
|
||||
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
|
||||
private volatile SettingsHotloadWatch settingsHotloadWatch;
|
||||
private volatile Thread serverLifecycleThread;
|
||||
|
||||
public static VolmitSender getSender() {
|
||||
VolmitSender current = sender;
|
||||
@@ -540,6 +540,17 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
this::getIrisVersion,
|
||||
this::getMCVersion));
|
||||
SlimJar.load();
|
||||
restoreAttachSignal();
|
||||
}
|
||||
|
||||
private static void restoreAttachSignal() {
|
||||
try {
|
||||
if (AttachSignal.restoreJvmHandler()) {
|
||||
info("Restored the JVM SIGQUIT handler that the server console replaced");
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
reportError("Could not restore the JVM SIGQUIT handler; the Iris agent may fail to attach.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void bridgeLog(LogLevel level, String message) {
|
||||
@@ -746,7 +757,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
|
||||
public void addShutdownHook() {
|
||||
removeShutdownHook();
|
||||
serverLifecycleThread = Thread.currentThread();
|
||||
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
|
||||
try {
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
@@ -877,6 +887,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
pendingWorldReplacements.awaitStagingForShutdown();
|
||||
teardownPapi();
|
||||
boolean serverStopping = IrisToolbelt.isServerStopping();
|
||||
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
|
||||
@@ -1012,7 +1023,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
if (generator == null) {
|
||||
continue;
|
||||
}
|
||||
IrisToolbelt.beginWorldMaintenance(world, reason, true);
|
||||
IrisToolbelt.beginWorldMaintenance(world, reason);
|
||||
if (!deferredShutdownGenerators.contains(generator)) {
|
||||
deferredShutdownGenerators.add(generator);
|
||||
}
|
||||
@@ -1024,51 +1035,31 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
if (!postStopFinisherStarted.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
Thread activeServerThread = serverLifecycleThread;
|
||||
if (activeServerThread == null) {
|
||||
Iris.warn("Iris could not start its post-stop runtime finisher because the server lifecycle thread is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
Thread finisher = new Thread(() -> {
|
||||
if (!awaitServerThreadTermination(activeServerThread)) {
|
||||
return;
|
||||
}
|
||||
finishDeferredRuntimeTeardown("post-server-stop", 30L);
|
||||
}, "Iris-PostStop-Finisher");
|
||||
Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"),
|
||||
"Iris-PostStop-Finisher");
|
||||
finisher.setDaemon(false);
|
||||
finisher.start();
|
||||
}
|
||||
|
||||
static boolean awaitServerThreadTermination(Thread serverThread) {
|
||||
if (serverThread == null || serverThread == Thread.currentThread()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
serverThread.join();
|
||||
return true;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Iris.reportError("Iris post-stop runtime finisher was interrupted.", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void runShutdownHook() {
|
||||
if (startupBoundaryRestart.get()) {
|
||||
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
|
||||
return;
|
||||
}
|
||||
finishRuntimeAfterServerShutdown("shutdown-hook");
|
||||
}
|
||||
|
||||
private void finishRuntimeAfterServerShutdown(String reason) {
|
||||
if (!awaitServerShutdownBoundary()) {
|
||||
Iris.warn("Iris skipped JVM-hook runtime teardown because Paper did not reach its post-world-close boundary.");
|
||||
Iris.warn("Iris retained its runtime and plugin class loader because the server did not reach its post-world-close boundary.");
|
||||
return;
|
||||
}
|
||||
finishDeferredRuntimeTeardown("shutdown-hook", 30L);
|
||||
finishDeferredRuntimeTeardown(reason, 30L);
|
||||
}
|
||||
|
||||
private boolean awaitServerShutdownBoundary() {
|
||||
if (!INMS.isBound()) {
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return INMS.get().awaitServerShutdownBoundary(
|
||||
@@ -1281,12 +1272,15 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
public int getIrisVersion() {
|
||||
String input = getDescription().getVersion();
|
||||
int hyphenIndex = input.indexOf('-');
|
||||
if (hyphenIndex != -1) {
|
||||
String result = input.substring(0, hyphenIndex);
|
||||
result = result.replaceAll("\\.", "");
|
||||
return Integer.parseInt(result);
|
||||
String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex);
|
||||
if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) {
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(release.replace(".", ""));
|
||||
} catch (NumberFormatException invalid) {
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getMCVersion() {
|
||||
|
||||
+58
-1
@@ -55,6 +55,7 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
@@ -73,6 +74,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
private volatile UUID overworldEntryAwaitingVerification;
|
||||
private volatile World overworldEntryWorld;
|
||||
private volatile boolean paperEntryListenerRegistered;
|
||||
private final Object stagingMonitor = new Object();
|
||||
private boolean stagingAdmissionOpen = true;
|
||||
private StagingAdmission activeStaging;
|
||||
|
||||
public PendingWorldReplacementManager(Iris plugin) {
|
||||
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
||||
@@ -135,7 +139,7 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
|
||||
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
|
||||
requiredWorldKey.toString()
|
||||
)) {
|
||||
); StagingAdmission stagingAdmission = admitStaging(requiredWorldKey)) {
|
||||
if (findTransaction(requiredWorldSlotKey) != null) {
|
||||
throw new IOException("A replacement is already pending for " + requiredWorldKey + ".");
|
||||
}
|
||||
@@ -251,6 +255,29 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
public void awaitStagingForShutdown() {
|
||||
StagingAdmission staging;
|
||||
synchronized (stagingMonitor) {
|
||||
stagingAdmissionOpen = false;
|
||||
staging = activeStaging;
|
||||
}
|
||||
if (staging == null) {
|
||||
return;
|
||||
}
|
||||
Iris.warn("Waiting for the replacement of " + staging.worldKey + " to finish staging before Iris shuts down.");
|
||||
boolean interrupted = false;
|
||||
while (staging.finished.getCount() > 0L) {
|
||||
try {
|
||||
staging.finished.await();
|
||||
} catch (InterruptedException e) {
|
||||
interrupted = true;
|
||||
}
|
||||
}
|
||||
if (interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void processPendingStartupReplacements() {
|
||||
ArrayList<String> failures = new ArrayList<>();
|
||||
ArrayList<String> restartBoundaries = new ArrayList<>();
|
||||
@@ -993,6 +1020,17 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
StagingAdmission admitStaging(NamespacedKey worldKey) throws IOException {
|
||||
synchronized (stagingMonitor) {
|
||||
if (!stagingAdmissionOpen) {
|
||||
throw new IOException("Iris is shutting down. Run the replacement again after the server starts.");
|
||||
}
|
||||
StagingAdmission staging = new StagingAdmission(worldKey);
|
||||
activeStaging = staging;
|
||||
return staging;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void loadOverworldEntryGuard() throws IOException {
|
||||
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
|
||||
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
|
||||
@@ -1157,6 +1195,25 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
final class StagingAdmission implements AutoCloseable {
|
||||
private final NamespacedKey worldKey;
|
||||
private final CountDownLatch finished = new CountDownLatch(1);
|
||||
|
||||
private StagingAdmission(NamespacedKey worldKey) {
|
||||
this.worldKey = worldKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (stagingMonitor) {
|
||||
if (activeStaging == this) {
|
||||
activeStaging = null;
|
||||
}
|
||||
}
|
||||
finished.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RestartBoundaryRequired extends IOException {
|
||||
private RestartBoundaryRequired(String message) {
|
||||
super(message);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package art.arcane.iris.core.agent;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.FunctionDescriptor;
|
||||
import java.lang.foreign.Linker;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.util.Locale;
|
||||
|
||||
public final class AttachSignal {
|
||||
private static final int SIGQUIT = 3;
|
||||
private static final int SIGTERM = 15;
|
||||
private static final long ACTION_BYTES = 256;
|
||||
private static final long SIG_IGN = 1L;
|
||||
|
||||
private AttachSignal() {
|
||||
}
|
||||
|
||||
public static boolean restoreJvmHandler() {
|
||||
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
|
||||
return false;
|
||||
}
|
||||
Linker linker = Linker.nativeLinker();
|
||||
MethodHandle sigaction = linker.downcallHandle(
|
||||
linker.defaultLookup().find("sigaction")
|
||||
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
|
||||
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment jvm = arena.allocate(ACTION_BYTES);
|
||||
MemorySegment quit = arena.allocate(ACTION_BYTES);
|
||||
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|
||||
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
|
||||
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
|
||||
}
|
||||
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
|
||||
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
|
||||
return false;
|
||||
}
|
||||
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
|
||||
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
|
||||
}
|
||||
return true;
|
||||
} catch (RuntimeException | Error failure) {
|
||||
throw failure;
|
||||
} catch (Throwable failure) {
|
||||
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,7 +510,7 @@ public class CommandIris implements DirectorExecutor {
|
||||
return;
|
||||
}
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
||||
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
|
||||
try {
|
||||
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
||||
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
|
||||
@@ -522,6 +522,8 @@ public class CommandIris implements DirectorExecutor {
|
||||
if (!Boolean.TRUE.equals(evacuated)) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
||||
maintenanceEntered.set(true);
|
||||
return WorldLifecycleService.get().unloadAsync(world, true);
|
||||
})
|
||||
.thenCompose(unloaded -> {
|
||||
@@ -536,7 +538,9 @@ public class CommandIris implements DirectorExecutor {
|
||||
});
|
||||
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
|
||||
.whenComplete((unloaded, throwable) -> {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
if (maintenanceEntered.get()) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
}
|
||||
lease.close();
|
||||
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
|
||||
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
|
||||
@@ -545,7 +549,9 @@ public class CommandIris implements DirectorExecutor {
|
||||
J.s(response);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
if (maintenanceEntered.get()) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
}
|
||||
lease.close();
|
||||
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_FAILED_UNLOAD_WORLD_3, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
|
||||
Iris.reportError("Failed to unload world \"" + world.getName() + "\".", e);
|
||||
|
||||
+20
-11
@@ -24,9 +24,10 @@ public class IrisShutdownOrderingTest {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
|
||||
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
|
||||
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
|
||||
String shutdownHook = section(source, "private void runShutdownHook()", "private boolean awaitServerShutdownBoundary");
|
||||
String finisher = section(source, "private void startPostStopFinisher()", "static boolean awaitServerThreadTermination");
|
||||
String serverJoin = section(source, "static boolean awaitServerThreadTermination", "private void runShutdownHook");
|
||||
String shutdownHook = section(source, "private void runShutdownHook()", "private void finishRuntimeAfterServerShutdown");
|
||||
String boundaryFinish = section(source, "private void finishRuntimeAfterServerShutdown", "private boolean awaitServerShutdownBoundary");
|
||||
String boundaryAwait = section(source, "private boolean awaitServerShutdownBoundary", "private void finishDeferredRuntimeTeardown");
|
||||
String finisher = section(source, "private void startPostStopFinisher()", "private void runShutdownHook");
|
||||
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
|
||||
String generatorQuiesce = section(generatorSource,
|
||||
"public void quiesceForServerShutdown()", "public boolean isStudio()");
|
||||
@@ -43,17 +44,19 @@ public class IrisShutdownOrderingTest {
|
||||
"startupBoundaryRestart.get()",
|
||||
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
|
||||
"return;",
|
||||
"awaitServerShutdownBoundary()",
|
||||
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
|
||||
"finishRuntimeAfterServerShutdown(\"shutdown-hook\")");
|
||||
assertOrdered(finisher,
|
||||
"finishRuntimeAfterServerShutdown(\"post-server-stop\")",
|
||||
"finisher.setDaemon(false)",
|
||||
"finisher.start()");
|
||||
assertOrdered(finisher,
|
||||
"awaitServerThreadTermination(activeServerThread)",
|
||||
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
|
||||
assertOrdered(serverJoin,
|
||||
"serverThread == Thread.currentThread()",
|
||||
"serverThread.join()");
|
||||
assertOrdered(boundaryFinish,
|
||||
"awaitServerShutdownBoundary()",
|
||||
"return;",
|
||||
"finishDeferredRuntimeTeardown(reason, 30L)");
|
||||
assertTrue("A missing shutdown boundary must retain the runtime",
|
||||
boundaryAwait.contains("if (!INMS.isBound()) {\n return false;"));
|
||||
assertFalse("Runtime cleanup must wait for the shutdown boundary, not the server thread",
|
||||
source.contains("serverThread.join()") || source.contains("serverLifecycleThread"));
|
||||
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
|
||||
quiesce.contains("generator.quiesceForServerShutdown()"));
|
||||
assertOrdered(quiesce,
|
||||
@@ -63,6 +66,12 @@ public class IrisShutdownOrderingTest {
|
||||
assertOrdered(onDisable,
|
||||
"quiesceRuntimeForServerShutdown(\"onDisable\")",
|
||||
"super.onDisable()");
|
||||
assertTrue("Server-stop quiescence must keep queued generation running its mantle stages",
|
||||
quiesce.contains("IrisToolbelt.beginWorldMaintenance(world, reason);"));
|
||||
assertTrue("Disable must wait for a replacement that is staging before it tears anything down",
|
||||
onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()") >= 0
|
||||
&& onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()")
|
||||
< onDisable.indexOf("teardownPapi()"));
|
||||
assertFalse("Server-stop quiescence must not begin generator close before Paper's boundary",
|
||||
generatorQuiesce.contains("closing = true"));
|
||||
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Answers.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
public class IrisVersionNumberTest {
|
||||
@Test
|
||||
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
|
||||
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
|
||||
assertEquals(version, 433, plugin(version).getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void processedPluginMetadataProvidesAValidEngineVersion() throws Exception {
|
||||
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
|
||||
assertNotNull(stream);
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(new PluginDescriptionFile(stream)).when(plugin).getDescription();
|
||||
|
||||
assertNotEquals(-1, plugin.getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
|
||||
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
|
||||
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
|
||||
assertEquals(version, -1, plugin(version).getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
private static Iris plugin(String version) {
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+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();
|
||||
|
||||
assertTrue("onDisable must tear the expansion down",
|
||||
source.contains("public void onDisable() {\n teardownPapi();"));
|
||||
source.contains("public void onDisable() {\n pendingWorldReplacements.awaitStagingForShutdown();\n teardownPapi();"));
|
||||
assertTrue("the BileTools pre-unload hook must tear the expansion down",
|
||||
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user