feat(sentinel): alert on repeated suspicious movement
This commit is contained in:
1 parent
8801e2f1b9
commit
b211e9d337
54 files changed
+3272
-2
No files matched your search
@@ -0,0 +1,6 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record AlertDecision(UUID playerId, int breachCount, double peakSpeed, double capturedLimit) {
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.LinkedHashMap;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
public final class AtomicYamlSettingsStore implements SettingsPersistence {
|
||||
private final Path file;
|
||||
|
||||
public AtomicYamlSettingsStore(Path file) {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public static void writeDefaults(Path file) throws IOException {
|
||||
if (Files.notExists(file)) {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, """
|
||||
horizontal-speed-limit: 0.80
|
||||
breaches-to-alert: 6
|
||||
evidence-window-seconds: 10
|
||||
alert-cooldown-seconds: 60
|
||||
minimum-tps: 18.0
|
||||
exemption-grace-ticks: 20
|
||||
""", StandardOpenOption.CREATE_NEW);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public SettingsDocument load() throws IOException {
|
||||
if (Files.notExists(file)) {
|
||||
throw new IOException("Missing Sentinel configuration: " + file);
|
||||
}
|
||||
var yaml = YamlConfiguration.loadConfiguration(file.toFile());
|
||||
var values = new LinkedHashMap<String, Object>();
|
||||
for (String key : yaml.getKeys(false)) {
|
||||
values.put(key, yaml.get(key));
|
||||
}
|
||||
return new SettingsDocument(values);
|
||||
}
|
||||
|
||||
@Override public void save(SettingsDocument document) throws IOException {
|
||||
var yaml = new YamlConfiguration();
|
||||
document.values().forEach(yaml::set);
|
||||
byte[] bytes = yaml.saveToString().getBytes(StandardCharsets.UTF_8);
|
||||
Path parent = file.toAbsolutePath().getParent();
|
||||
Files.createDirectories(parent);
|
||||
Path temporary = Files.createTempFile(parent, file.getFileName().toString(), ".tmp");
|
||||
boolean moved = false;
|
||||
try {
|
||||
try (var channel = FileChannel.open(temporary, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
var buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
try {
|
||||
Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException exception) {
|
||||
throw new IOException("Atomic configuration replacement is not supported", exception);
|
||||
}
|
||||
moved = true;
|
||||
} finally {
|
||||
if (!moved) Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Supplier;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Pose;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.entity.EntityDamageEvent;
|
||||
import org.bukkit.event.entity.EntityKnockbackEvent;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.player.PlayerVelocityEvent;
|
||||
|
||||
public final class BukkitMovementListener implements Listener {
|
||||
private final Server server;
|
||||
private final MovementMonitor monitor;
|
||||
private final Supplier<SentinelSettings> settings;
|
||||
private final LongSupplier nanoTime;
|
||||
private final BiPredicate<Location, Location> ordinaryEnvironment;
|
||||
|
||||
public BukkitMovementListener(Server server, MovementMonitor monitor, Supplier<SentinelSettings> settings, LongSupplier nanoTime) {
|
||||
this(server, monitor, settings, nanoTime,
|
||||
(from, to) -> MovementEnvironment.isOrdinary(from) && MovementEnvironment.isOrdinary(to));
|
||||
}
|
||||
|
||||
BukkitMovementListener(Server server, MovementMonitor monitor, Supplier<SentinelSettings> settings,
|
||||
LongSupplier nanoTime, BiPredicate<Location, Location> ordinaryEnvironment) {
|
||||
this.server = server;
|
||||
this.monitor = monitor;
|
||||
this.settings = settings;
|
||||
this.nanoTime = nanoTime;
|
||||
this.ordinaryEnvironment = ordinaryEnvironment;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
if (!event.hasExplicitlyChangedPosition()) return;
|
||||
Location from = event.getFrom();
|
||||
Location to = event.getTo();
|
||||
var player = event.getPlayer();
|
||||
ExclusionReason reason = classify(player, from, to, event.isCancelled());
|
||||
monitor.record(player.getUniqueId(), new MovementFrame(
|
||||
server.getCurrentTick(),
|
||||
nanoTime.getAsLong(),
|
||||
Objects.requireNonNull(from.getWorld()).getUID(),
|
||||
Objects.requireNonNull(to.getWorld()).getUID(),
|
||||
from.getX(), from.getZ(), to.getX(), to.getZ(), reason), settings.get());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
|
||||
public void onTeleport(PlayerTeleportEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onJoin(PlayerJoinEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onRespawn(PlayerRespawnEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onWorldChange(PlayerChangedWorldEvent event) { exempt(event.getPlayer(), ExclusionReason.LIFECYCLE); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onVelocity(PlayerVelocityEvent event) { exempt(event.getPlayer(), ExclusionReason.VELOCITY); }
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onKnockback(EntityKnockbackEvent event) {
|
||||
if (event.getEntity() instanceof Player player) exempt(player, ExclusionReason.VELOCITY);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onDamage(EntityDamageEvent event) {
|
||||
if (event.getEntity() instanceof Player player) exempt(player, ExclusionReason.DAMAGE);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onQuit(PlayerQuitEvent event) { monitor.forget(event.getPlayer().getUniqueId()); }
|
||||
|
||||
private void exempt(Player player, ExclusionReason reason) {
|
||||
monitor.exempt(player.getUniqueId(), server.getCurrentTick(), nanoTime.getAsLong(), reason, settings.get());
|
||||
}
|
||||
|
||||
private ExclusionReason classify(Player player, Location from, Location to, boolean cancelled) {
|
||||
if (cancelled) return ExclusionReason.CANCELLED;
|
||||
if (from.getWorld() == null || to.getWorld() == null || !from.getWorld().equals(to.getWorld())) return ExclusionReason.INCOMPLETE;
|
||||
if (!finite(from.getX(), from.getZ(), to.getX(), to.getZ())) return ExclusionReason.INCOMPLETE;
|
||||
if (server.getTPS()[0] < settings.get().minimumTps()) return ExclusionReason.LOW_TPS;
|
||||
if (player.getGameMode() != GameMode.SURVIVAL && player.getGameMode() != GameMode.ADVENTURE) return ExclusionReason.GAME_MODE;
|
||||
if (player.isInsideVehicle()) return ExclusionReason.VEHICLE;
|
||||
if (player.isFlying()) return ExclusionReason.FLYING;
|
||||
if (player.isGliding() || player.getPose() == Pose.FALL_FLYING) return ExclusionReason.GLIDING;
|
||||
if (player.isSwimming() || player.getPose() == Pose.SWIMMING || player.isInWater()
|
||||
|| player.isInLava() || player.isInBubbleColumn()) return ExclusionReason.SWIMMING;
|
||||
if (player.isClimbing()) return ExclusionReason.CLIMBING;
|
||||
if (player.isRiptiding() || player.getPose() == Pose.SPIN_ATTACK) return ExclusionReason.RIPTIDE;
|
||||
if (player.getActivePotionEffects().stream().map(effect -> effect.getType().getKey().getKey())
|
||||
.anyMatch(key -> key.equals("speed") || key.equals("slowness"))) {
|
||||
return ExclusionReason.POTION_EFFECT;
|
||||
}
|
||||
if (!ordinaryEnvironment.test(from, to)) return ExclusionReason.ENVIRONMENT;
|
||||
return ExclusionReason.NONE;
|
||||
}
|
||||
|
||||
private static boolean finite(double... values) {
|
||||
for (double value : values) if (!Double.isFinite(value)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
public enum ExclusionReason {
|
||||
NONE("none"),
|
||||
CANCELLED("cancelled movement"),
|
||||
INCOMPLETE("incomplete movement"),
|
||||
GAME_MODE("game mode"),
|
||||
VEHICLE("vehicle"),
|
||||
FLYING("flight"),
|
||||
GLIDING("gliding"),
|
||||
SWIMMING("swimming or crawling"),
|
||||
CLIMBING("climbing"),
|
||||
RIPTIDE("riptide"),
|
||||
POTION_EFFECT("speed or slowness effect"),
|
||||
ENVIRONMENT("movement-altering environment"),
|
||||
LOW_TPS("low server TPS"),
|
||||
LIFECYCLE("join, teleport, respawn, or world change"),
|
||||
VELOCITY("server-applied velocity or knockback"),
|
||||
DAMAGE("damage or explosion");
|
||||
|
||||
private final String description;
|
||||
|
||||
ExclusionReason(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
public record InspectionSnapshot(
|
||||
int breachCount,
|
||||
double evidenceAgeSeconds,
|
||||
double peakSpeed,
|
||||
double capturedLimit,
|
||||
ExclusionReason currentExclusion,
|
||||
double cooldownRemainingSeconds) {
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class MovementDetector {
|
||||
static final int MAX_EVIDENCE_PER_PLAYER = 1_200;
|
||||
private final Map<UUID, PlayerState> players = new HashMap<>();
|
||||
|
||||
public Optional<AlertDecision> observe(UUID playerId, MovementSample sample, SentinelSettings settings) {
|
||||
var state = players.computeIfAbsent(playerId, ignored -> new PlayerState());
|
||||
expire(state, sample.observedAtNanos());
|
||||
if (!sample.complete() || sample.cancelled() || sample.exclusionReason() != ExclusionReason.NONE
|
||||
|| !Double.isFinite(sample.horizontalDistance()) || sample.horizontalDistance() < 0) {
|
||||
state.currentExclusion = sample.cancelled() ? ExclusionReason.CANCELLED
|
||||
: sample.exclusionReason() == ExclusionReason.NONE ? ExclusionReason.INCOMPLETE : sample.exclusionReason();
|
||||
state.graceThroughTick = Math.max(state.graceThroughTick, sample.tick() + settings.exemptionGraceTicks());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (sample.tick() <= state.graceThroughTick) {
|
||||
return Optional.empty();
|
||||
}
|
||||
state.currentExclusion = ExclusionReason.NONE;
|
||||
if (sample.horizontalDistance() <= settings.horizontalSpeedLimit()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (state.evidence.size() == MAX_EVIDENCE_PER_PLAYER) {
|
||||
state.evidence.removeFirst();
|
||||
}
|
||||
state.evidence.addLast(new Breach(
|
||||
sample.observedAtNanos(),
|
||||
sample.observedAtNanos() + seconds(settings.evidenceWindowSeconds()),
|
||||
sample.horizontalDistance(),
|
||||
settings.horizontalSpeedLimit()));
|
||||
if (state.evidence.size() < settings.breachesToAlert() || sample.observedAtNanos() < state.cooldownUntilNanos) {
|
||||
return Optional.empty();
|
||||
}
|
||||
state.cooldownUntilNanos = sample.observedAtNanos() + seconds(settings.alertCooldownSeconds());
|
||||
var peak = state.evidence.stream().max(Comparator.comparingDouble(Breach::speed)).orElseThrow();
|
||||
return Optional.of(new AlertDecision(playerId, state.evidence.size(), peak.speed(), peak.capturedLimit()));
|
||||
}
|
||||
|
||||
public void exempt(UUID playerId, int currentTick, long nowNanos, ExclusionReason reason, SentinelSettings settings) {
|
||||
var state = players.computeIfAbsent(playerId, ignored -> new PlayerState());
|
||||
expire(state, nowNanos);
|
||||
state.currentExclusion = reason;
|
||||
state.graceThroughTick = Math.max(state.graceThroughTick, currentTick + settings.exemptionGraceTicks());
|
||||
}
|
||||
|
||||
public Optional<InspectionSnapshot> inspect(UUID playerId, long nowNanos) {
|
||||
var state = players.get(playerId);
|
||||
if (state == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
expire(state, nowNanos);
|
||||
if (state.evidence.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
var first = state.evidence.getFirst();
|
||||
var peak = state.evidence.stream().max(Comparator.comparingDouble(Breach::speed)).orElseThrow();
|
||||
return Optional.of(new InspectionSnapshot(
|
||||
state.evidence.size(),
|
||||
Math.max(0, nowNanos - first.observedAtNanos()) / 1_000_000_000.0,
|
||||
peak.speed(),
|
||||
peak.capturedLimit(),
|
||||
state.currentExclusion,
|
||||
Math.max(0, state.cooldownUntilNanos - nowNanos) / 1_000_000_000.0));
|
||||
}
|
||||
|
||||
public void cleanup(int currentTick, long nowNanos) {
|
||||
players.entrySet().removeIf(entry -> {
|
||||
var state = entry.getValue();
|
||||
expire(state, nowNanos);
|
||||
return state.evidence.isEmpty() && state.cooldownUntilNanos <= nowNanos
|
||||
&& currentTick > state.graceThroughTick;
|
||||
});
|
||||
}
|
||||
|
||||
public void forget(UUID playerId) {
|
||||
players.remove(playerId);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
players.clear();
|
||||
}
|
||||
|
||||
int trackedPlayerCount() {
|
||||
return players.size();
|
||||
}
|
||||
|
||||
int evidenceCount(UUID playerId) {
|
||||
var state = players.get(playerId);
|
||||
return state == null ? 0 : state.evidence.size();
|
||||
}
|
||||
|
||||
private static long seconds(int value) {
|
||||
return value * 1_000_000_000L;
|
||||
}
|
||||
|
||||
private static void expire(PlayerState state, long nowNanos) {
|
||||
while (!state.evidence.isEmpty() && state.evidence.getFirst().expiresAtNanos() <= nowNanos) {
|
||||
state.evidence.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
private record Breach(long observedAtNanos, long expiresAtNanos, double speed, double capturedLimit) {
|
||||
}
|
||||
|
||||
private static final class PlayerState {
|
||||
private final ArrayDeque<Breach> evidence = new ArrayDeque<>();
|
||||
private int graceThroughTick = Integer.MIN_VALUE;
|
||||
private long cooldownUntilNanos;
|
||||
private ExclusionReason currentExclusion = ExclusionReason.NONE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.Set;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.data.Waterlogged;
|
||||
|
||||
final class MovementEnvironment {
|
||||
private static final Set<Material> ALTERING = Set.of(
|
||||
Material.SLIME_BLOCK,
|
||||
Material.HONEY_BLOCK,
|
||||
Material.SOUL_SAND,
|
||||
Material.SOUL_SOIL,
|
||||
Material.BUBBLE_COLUMN,
|
||||
Material.PISTON,
|
||||
Material.STICKY_PISTON,
|
||||
Material.PISTON_HEAD,
|
||||
Material.MOVING_PISTON,
|
||||
Material.COBWEB,
|
||||
Material.POWDER_SNOW,
|
||||
Material.SCAFFOLDING,
|
||||
Material.SWEET_BERRY_BUSH);
|
||||
|
||||
private MovementEnvironment() {
|
||||
}
|
||||
|
||||
static boolean isOrdinary(Location location) {
|
||||
var world = location.getWorld();
|
||||
if (world == null || !world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {
|
||||
return false;
|
||||
}
|
||||
int baseX = location.getBlockX();
|
||||
int baseY = location.getBlockY();
|
||||
int baseZ = location.getBlockZ();
|
||||
for (int x = baseX - 1; x <= baseX + 1; x++) {
|
||||
for (int z = baseZ - 1; z <= baseZ + 1; z++) {
|
||||
for (int y = baseY - 1; y <= baseY + 1; y++) {
|
||||
var block = world.getBlockAt(x, y, z);
|
||||
var type = block.getType();
|
||||
if (ALTERING.contains(type) || isIce(type) || isClimbable(type) || block.isLiquid()) {
|
||||
return false;
|
||||
}
|
||||
if (block.getBlockData() instanceof Waterlogged waterlogged && waterlogged.isWaterlogged()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isIce(Material type) {
|
||||
return type == Material.ICE || type == Material.PACKED_ICE
|
||||
|| type == Material.BLUE_ICE || type == Material.FROSTED_ICE;
|
||||
}
|
||||
|
||||
private static boolean isClimbable(Material type) {
|
||||
String name = type.name();
|
||||
return type == Material.LADDER || type == Material.VINE || type == Material.SCAFFOLDING
|
||||
|| name.equals("WEEPING_VINES") || name.equals("WEEPING_VINES_PLANT")
|
||||
|| name.equals("TWISTING_VINES") || name.equals("TWISTING_VINES_PLANT")
|
||||
|| name.equals("CAVE_VINES") || name.equals("CAVE_VINES_PLANT");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record MovementFrame(
|
||||
int tick,
|
||||
long observedAtNanos,
|
||||
UUID fromWorld,
|
||||
UUID toWorld,
|
||||
double fromX,
|
||||
double fromZ,
|
||||
double toX,
|
||||
double toZ,
|
||||
ExclusionReason reason) {
|
||||
public MovementFrame withReason(ExclusionReason replacement) {
|
||||
return new MovementFrame(tick, observedAtNanos, fromWorld, toWorld, fromX, fromZ, toX, toZ, replacement);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class MovementMonitor {
|
||||
private static final double CHAIN_TOLERANCE = 1.0e-6;
|
||||
private final MovementDetector detector;
|
||||
private final Map<UUID, TickBucket> pending = new HashMap<>();
|
||||
|
||||
public MovementMonitor(MovementDetector detector) {
|
||||
this.detector = detector;
|
||||
}
|
||||
|
||||
public void record(UUID playerId, MovementFrame frame, SentinelSettings settings) {
|
||||
var existing = pending.get(playerId);
|
||||
if (existing != null && existing.tick != frame.tick()) {
|
||||
finish(playerId, existing);
|
||||
pending.remove(playerId);
|
||||
existing = null;
|
||||
}
|
||||
if (existing == null) {
|
||||
pending.put(playerId, TickBucket.start(frame, settings));
|
||||
} else {
|
||||
existing.add(frame);
|
||||
}
|
||||
}
|
||||
|
||||
public List<AlertDecision> finishBefore(int currentTick, long nowNanos) {
|
||||
var alerts = new ArrayList<AlertDecision>();
|
||||
var iterator = pending.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
var entry = iterator.next();
|
||||
if (entry.getValue().tick < currentTick) {
|
||||
finish(entry.getKey(), entry.getValue()).ifPresent(alerts::add);
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
detector.cleanup(currentTick, nowNanos);
|
||||
return List.copyOf(alerts);
|
||||
}
|
||||
|
||||
public void exempt(UUID playerId, int tick, long nowNanos, ExclusionReason reason, SentinelSettings settings) {
|
||||
pending.remove(playerId);
|
||||
detector.exempt(playerId, tick, nowNanos, reason, settings);
|
||||
}
|
||||
|
||||
public Optional<InspectionSnapshot> inspect(UUID playerId, long nowNanos) {
|
||||
return detector.inspect(playerId, nowNanos);
|
||||
}
|
||||
|
||||
public void forget(UUID playerId) {
|
||||
pending.remove(playerId);
|
||||
detector.forget(playerId);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
pending.clear();
|
||||
detector.clear();
|
||||
}
|
||||
|
||||
int trackedPlayerCount() {
|
||||
return detector.trackedPlayerCount();
|
||||
}
|
||||
|
||||
private Optional<AlertDecision> finish(UUID playerId, TickBucket bucket) {
|
||||
return detector.observe(playerId, new MovementSample(
|
||||
bucket.tick,
|
||||
bucket.observedAtNanos,
|
||||
!bucket.invalid,
|
||||
bucket.reason == ExclusionReason.CANCELLED,
|
||||
bucket.maximumDistance,
|
||||
bucket.reason), bucket.settings);
|
||||
}
|
||||
|
||||
private static final class TickBucket {
|
||||
private final int tick;
|
||||
private final long observedAtNanos;
|
||||
private final UUID world;
|
||||
private final double anchorX;
|
||||
private final double anchorZ;
|
||||
private final SentinelSettings settings;
|
||||
private double lastX;
|
||||
private double lastZ;
|
||||
private double previousFromX;
|
||||
private double previousFromZ;
|
||||
private double previousToX;
|
||||
private double previousToZ;
|
||||
private boolean hasPrevious;
|
||||
private double maximumDistance;
|
||||
private ExclusionReason reason;
|
||||
private boolean invalid;
|
||||
|
||||
private TickBucket(MovementFrame frame, SentinelSettings settings) {
|
||||
tick = frame.tick();
|
||||
observedAtNanos = frame.observedAtNanos();
|
||||
world = frame.fromWorld();
|
||||
anchorX = frame.fromX();
|
||||
anchorZ = frame.fromZ();
|
||||
this.settings = settings;
|
||||
lastX = frame.fromX();
|
||||
lastZ = frame.fromZ();
|
||||
reason = ExclusionReason.NONE;
|
||||
add(frame);
|
||||
}
|
||||
|
||||
static TickBucket start(MovementFrame frame, SentinelSettings settings) {
|
||||
return new TickBucket(frame, settings);
|
||||
}
|
||||
|
||||
void add(MovementFrame frame) {
|
||||
if (!world.equals(frame.toWorld()) || !world.equals(frame.fromWorld())
|
||||
|| !finite(frame.fromX(), frame.fromZ(), frame.toX(), frame.toZ())
|
||||
|| !connected(frame.fromX(), frame.fromZ())) {
|
||||
invalid = true;
|
||||
reason = ExclusionReason.INCOMPLETE;
|
||||
return;
|
||||
}
|
||||
if (frame.reason() != ExclusionReason.NONE) {
|
||||
invalid = true;
|
||||
reason = frame.reason();
|
||||
}
|
||||
maximumDistance = Math.max(maximumDistance, Math.hypot(frame.toX() - anchorX, frame.toZ() - anchorZ));
|
||||
if (!duplicate(frame)) {
|
||||
lastX = frame.toX();
|
||||
lastZ = frame.toZ();
|
||||
}
|
||||
previousFromX = frame.fromX();
|
||||
previousFromZ = frame.fromZ();
|
||||
previousToX = frame.toX();
|
||||
previousToZ = frame.toZ();
|
||||
hasPrevious = true;
|
||||
}
|
||||
|
||||
private boolean connected(double x, double z) {
|
||||
return near(x, anchorX) && near(z, anchorZ)
|
||||
|| near(x, lastX) && near(z, lastZ)
|
||||
|| hasPrevious && near(x, previousFromX) && near(z, previousFromZ);
|
||||
}
|
||||
|
||||
private boolean duplicate(MovementFrame frame) {
|
||||
return hasPrevious
|
||||
&& near(frame.fromX(), previousFromX) && near(frame.fromZ(), previousFromZ)
|
||||
&& near(frame.toX(), previousToX) && near(frame.toZ(), previousToZ);
|
||||
}
|
||||
|
||||
private static boolean near(double left, double right) {
|
||||
return Math.abs(left - right) <= CHAIN_TOLERANCE;
|
||||
}
|
||||
|
||||
private static boolean finite(double... values) {
|
||||
for (double value : values) {
|
||||
if (!Double.isFinite(value)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
public record MovementSample(
|
||||
int tick,
|
||||
long observedAtNanos,
|
||||
boolean complete,
|
||||
boolean cancelled,
|
||||
double horizontalDistance,
|
||||
ExclusionReason exclusionReason) {
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
|
||||
public final class PurpurSentinelPlugin extends JavaPlugin {
|
||||
private MovementMonitor monitor;
|
||||
private BukkitMovementListener listener;
|
||||
private BukkitTask tickTask;
|
||||
|
||||
@Override public void onEnable() {
|
||||
try {
|
||||
Files.createDirectories(getDataFolder().toPath());
|
||||
var configPath = getDataFolder().toPath().resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(configPath);
|
||||
var settings = SettingsService.load(new AtomicYamlSettingsStore(configPath));
|
||||
monitor = new MovementMonitor(new MovementDetector());
|
||||
listener = new BukkitMovementListener(getServer(), monitor, settings::current, System::nanoTime);
|
||||
var command = Objects.requireNonNull(getCommand("sentinel"), "Missing sentinel command");
|
||||
var handler = new SentinelCommand(getServer(), monitor, settings, System::nanoTime);
|
||||
command.setExecutor(handler);
|
||||
command.setTabCompleter(handler);
|
||||
getServer().getPluginManager().registerEvents(listener, this);
|
||||
var alerts = new SentinelAlerts(getServer());
|
||||
tickTask = getServer().getScheduler().runTaskTimer(this, () -> monitor
|
||||
.finishBefore(getServer().getCurrentTick(), System.nanoTime()).forEach(alerts::send), 1L, 1L);
|
||||
} catch (IOException | IllegalArgumentException exception) {
|
||||
getLogger().severe("Sentinel configuration is invalid or unavailable; observation was not activated: " + exception.getMessage());
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
if (tickTask != null) {
|
||||
tickTask.cancel();
|
||||
tickTask = null;
|
||||
}
|
||||
if (listener != null) {
|
||||
HandlerList.unregisterAll(listener);
|
||||
listener = null;
|
||||
}
|
||||
if (monitor != null) {
|
||||
monitor.clear();
|
||||
monitor = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.Locale;
|
||||
import org.bukkit.Server;
|
||||
|
||||
final class SentinelAlerts {
|
||||
private final Server server;
|
||||
|
||||
SentinelAlerts(Server server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
void send(AlertDecision alert) {
|
||||
var subject = server.getPlayer(alert.playerId());
|
||||
if (subject == null || !subject.isOnline()) return;
|
||||
String message = String.format(Locale.ROOT,
|
||||
"[Sentinel] %s: %d movement breaches; peak %.2f blocks/tick vs captured limit %.2f. Use /sentinel inspect %s.",
|
||||
subject.getName(), alert.breachCount(), alert.peakSpeed(), alert.capturedLimit(), subject.getName());
|
||||
server.getOnlinePlayers().stream()
|
||||
.filter(recipient -> recipient.hasPermission("sentinel.alerts"))
|
||||
.forEach(recipient -> recipient.sendMessage(message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.function.LongSupplier;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public final class SentinelCommand implements CommandExecutor, TabCompleter {
|
||||
private final Server server;
|
||||
private final MovementMonitor monitor;
|
||||
private final SettingsService settings;
|
||||
private final LongSupplier nanoTime;
|
||||
|
||||
public SentinelCommand(Server server, MovementMonitor monitor, SettingsService settings, LongSupplier nanoTime) {
|
||||
this.server = server;
|
||||
this.monitor = monitor;
|
||||
this.settings = settings;
|
||||
this.nanoTime = nanoTime;
|
||||
}
|
||||
|
||||
@Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
|
||||
@NotNull String label, @NotNull String[] args) {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage("Usage: /sentinel <inspect|config> ...");
|
||||
return true;
|
||||
}
|
||||
if (args[0].equalsIgnoreCase("inspect")) return inspect(sender, args);
|
||||
if (args[0].equalsIgnoreCase("config")) return configure(sender, args);
|
||||
sender.sendMessage("Unsupported Sentinel route: " + args[0] + '.');
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
|
||||
@NotNull String alias, @NotNull String[] args) {
|
||||
if (args.length == 1) {
|
||||
var routes = new ArrayList<String>();
|
||||
if (sender.hasPermission("sentinel.config")) routes.add("config");
|
||||
if (sender.hasPermission("sentinel.inspect")) routes.add("inspect");
|
||||
return filter(routes, args[0]);
|
||||
}
|
||||
if (args.length == 2 && args[0].equalsIgnoreCase("inspect") && sender.hasPermission("sentinel.inspect")) {
|
||||
return filter(server.getOnlinePlayers().stream().map(Player::getName)
|
||||
.sorted(String.CASE_INSENSITIVE_ORDER).toList(), args[1]);
|
||||
}
|
||||
if (args.length == 2 && args[0].equalsIgnoreCase("config") && sender.hasPermission("sentinel.config")) {
|
||||
return filter(java.util.Arrays.stream(SettingKey.values()).map(SettingKey::key).toList(), args[1]);
|
||||
}
|
||||
if (args.length == 3 && args[0].equalsIgnoreCase("config") && sender.hasPermission("sentinel.config")) {
|
||||
var key = SettingKey.find(args[1]);
|
||||
if (key.isEmpty()) return List.of();
|
||||
var values = new LinkedHashSet<String>();
|
||||
values.add(key.get().minimum());
|
||||
values.add(settings.value(key.get()));
|
||||
values.add(key.get().maximum());
|
||||
return filter(new ArrayList<>(values), args[2]);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private boolean inspect(CommandSender sender, String[] args) {
|
||||
if (!sender.hasPermission("sentinel.inspect")) {
|
||||
sender.sendMessage("You do not have permission to inspect Sentinel evidence.");
|
||||
return true;
|
||||
}
|
||||
if (args.length != 2) {
|
||||
sender.sendMessage("Usage: /sentinel inspect <player>");
|
||||
return true;
|
||||
}
|
||||
var player = server.getOnlinePlayers().stream()
|
||||
.filter(candidate -> candidate.getName().equalsIgnoreCase(args[1]))
|
||||
.findFirst();
|
||||
if (player.isEmpty()) {
|
||||
if (server.getOfflinePlayerIfCached(args[1]) != null) {
|
||||
sender.sendMessage(args[1] + " is offline; Sentinel retains no offline evidence.");
|
||||
} else {
|
||||
sender.sendMessage("Unknown player: " + args[1] + '.');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
var snapshot = monitor.inspect(player.get().getUniqueId(), nanoTime.getAsLong());
|
||||
if (snapshot.isEmpty()) {
|
||||
sender.sendMessage("No current evidence for " + player.get().getName() + "; none was recorded or it expired.");
|
||||
return true;
|
||||
}
|
||||
var evidence = snapshot.get();
|
||||
sender.sendMessage(String.format(Locale.ROOT,
|
||||
"%s: %d breaches; age %.1fs; peak %.2f blocks/tick vs captured limit %.2f; exclusion %s; cooldown %.1fs.",
|
||||
player.get().getName(), evidence.breachCount(), evidence.evidenceAgeSeconds(), evidence.peakSpeed(),
|
||||
evidence.capturedLimit(), evidence.currentExclusion().description(), evidence.cooldownRemainingSeconds()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean configure(CommandSender sender, String[] args) {
|
||||
if (!sender.hasPermission("sentinel.config")) {
|
||||
sender.sendMessage("You do not have permission to configure Sentinel.");
|
||||
return true;
|
||||
}
|
||||
if (args.length < 2 || args.length > 3) {
|
||||
sender.sendMessage("Usage: /sentinel config <key> [value]");
|
||||
return true;
|
||||
}
|
||||
var key = SettingKey.find(args[1]);
|
||||
if (key.isEmpty()) {
|
||||
sender.sendMessage("Unknown Sentinel configuration key: " + args[1] + '.');
|
||||
return true;
|
||||
}
|
||||
if (args.length == 2) {
|
||||
sender.sendMessage(key.get().key() + " is " + settings.value(key.get()) + '.');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
String value = settings.update(key.get(), args[2]);
|
||||
sender.sendMessage(key.get().key() + " updated to " + value + '.');
|
||||
} catch (IllegalArgumentException exception) {
|
||||
sender.sendMessage(exception.getMessage());
|
||||
} catch (IOException exception) {
|
||||
sender.sendMessage("Could not save Sentinel configuration; the prior value remains active.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<String> filter(List<String> options, String prefix) {
|
||||
String normalized = prefix.toLowerCase(Locale.ROOT);
|
||||
return options.stream().filter(value -> value.toLowerCase(Locale.ROOT).startsWith(normalized))
|
||||
.sorted(Comparator.comparing(value -> value.toLowerCase(Locale.ROOT))).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
public record SentinelSettings(
|
||||
double horizontalSpeedLimit,
|
||||
int breachesToAlert,
|
||||
int evidenceWindowSeconds,
|
||||
int alertCooldownSeconds,
|
||||
double minimumTps,
|
||||
int exemptionGraceTicks) {
|
||||
public SentinelSettings {
|
||||
requireFiniteRange(horizontalSpeedLimit, 0.40, 5.00, "horizontal-speed-limit");
|
||||
requireRange(breachesToAlert, 3, 40, "breaches-to-alert");
|
||||
requireRange(evidenceWindowSeconds, 2, 60, "evidence-window-seconds");
|
||||
requireRange(alertCooldownSeconds, 5, 3600, "alert-cooldown-seconds");
|
||||
requireFiniteRange(minimumTps, 10.0, 20.0, "minimum-tps");
|
||||
requireRange(exemptionGraceTicks, 1, 200, "exemption-grace-ticks");
|
||||
}
|
||||
|
||||
public static SentinelSettings defaults() {
|
||||
return new SentinelSettings(0.80, 6, 10, 60, 18.0, 20);
|
||||
}
|
||||
|
||||
private static void requireRange(int value, int minimum, int maximum, String key) {
|
||||
if (value < minimum || value > maximum) {
|
||||
throw new IllegalArgumentException(key + " must be between " + minimum + " and " + maximum + '.');
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireFiniteRange(double value, double minimum, double maximum, String key) {
|
||||
if (!Double.isFinite(value) || value < minimum || value > maximum) {
|
||||
throw new IllegalArgumentException(key + " must be between " + minimum + " and " + maximum + '.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
public enum SettingKey {
|
||||
HORIZONTAL_SPEED_LIMIT("horizontal-speed-limit", "0.40", "5.00", false),
|
||||
BREACHES_TO_ALERT("breaches-to-alert", "3", "40", true),
|
||||
EVIDENCE_WINDOW_SECONDS("evidence-window-seconds", "2", "60", true),
|
||||
ALERT_COOLDOWN_SECONDS("alert-cooldown-seconds", "5", "3600", true),
|
||||
MINIMUM_TPS("minimum-tps", "10.0", "20.0", false),
|
||||
EXEMPTION_GRACE_TICKS("exemption-grace-ticks", "1", "200", true);
|
||||
|
||||
private final String key;
|
||||
private final String minimum;
|
||||
private final String maximum;
|
||||
private final boolean integer;
|
||||
|
||||
SettingKey(String key, String minimum, String maximum, boolean integer) {
|
||||
this.key = key;
|
||||
this.minimum = minimum;
|
||||
this.maximum = maximum;
|
||||
this.integer = integer;
|
||||
}
|
||||
|
||||
public String key() { return key; }
|
||||
public String minimum() { return minimum; }
|
||||
public String maximum() { return maximum; }
|
||||
public boolean integer() { return integer; }
|
||||
|
||||
public static Optional<SettingKey> find(String value) {
|
||||
return Arrays.stream(values()).filter(key -> key.key.equals(value.toLowerCase(Locale.ROOT))).findFirst();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public record SettingsDocument(Map<String, Object> values) {
|
||||
public SettingsDocument {
|
||||
values = new LinkedHashMap<>(values);
|
||||
}
|
||||
|
||||
public SettingsDocument with(SettingKey key, Object value) {
|
||||
var copy = new LinkedHashMap<>(values);
|
||||
copy.put(key.key(), value);
|
||||
return new SettingsDocument(copy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public interface SettingsPersistence {
|
||||
SettingsDocument load() throws IOException;
|
||||
void save(SettingsDocument document) throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
public final class SettingsService {
|
||||
private final SettingsPersistence persistence;
|
||||
private final AtomicReference<SentinelSettings> current;
|
||||
|
||||
private SettingsService(SettingsPersistence persistence, SentinelSettings settings) {
|
||||
this.persistence = persistence;
|
||||
current = new AtomicReference<>(settings);
|
||||
}
|
||||
|
||||
public static SettingsService load(SettingsPersistence persistence) throws IOException {
|
||||
return new SettingsService(persistence, parse(persistence.load().values()));
|
||||
}
|
||||
|
||||
public SentinelSettings current() {
|
||||
return current.get();
|
||||
}
|
||||
|
||||
public synchronized String update(SettingKey key, String rawValue) throws IOException {
|
||||
Object parsedValue = parseValue(key, rawValue);
|
||||
var latest = persistence.load();
|
||||
var nextDocument = latest.with(key, parsedValue);
|
||||
var nextSettings = parse(nextDocument.values());
|
||||
persistence.save(nextDocument);
|
||||
current.set(nextSettings);
|
||||
return format(key, nextSettings);
|
||||
}
|
||||
|
||||
public String value(SettingKey key) {
|
||||
return format(key, current());
|
||||
}
|
||||
|
||||
private static SentinelSettings parse(Map<String, Object> values) {
|
||||
return new SentinelSettings(
|
||||
decimal(values, SettingKey.HORIZONTAL_SPEED_LIMIT),
|
||||
integer(values, SettingKey.BREACHES_TO_ALERT),
|
||||
integer(values, SettingKey.EVIDENCE_WINDOW_SECONDS),
|
||||
integer(values, SettingKey.ALERT_COOLDOWN_SECONDS),
|
||||
decimal(values, SettingKey.MINIMUM_TPS),
|
||||
integer(values, SettingKey.EXEMPTION_GRACE_TICKS));
|
||||
}
|
||||
|
||||
private static Object parseValue(SettingKey key, String value) {
|
||||
try {
|
||||
if (key.integer()) {
|
||||
if (!value.matches("-?(0|[1-9][0-9]*)")) throw new NumberFormatException();
|
||||
return Integer.parseInt(value);
|
||||
}
|
||||
double parsed = Double.parseDouble(value);
|
||||
if (!Double.isFinite(parsed)) throw new NumberFormatException();
|
||||
return parsed;
|
||||
} catch (NumberFormatException exception) {
|
||||
throw new IllegalArgumentException("Invalid value for " + key.key() + '.', exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static int integer(Map<String, Object> values, SettingKey key) {
|
||||
Object value = required(values, key);
|
||||
if (!(value instanceof Number number)) throw new IllegalArgumentException(key.key() + " must be an integer.");
|
||||
double decimal = number.doubleValue();
|
||||
if (!Double.isFinite(decimal) || decimal != Math.rint(decimal)) {
|
||||
throw new IllegalArgumentException(key.key() + " must be an integer.");
|
||||
}
|
||||
return Math.toIntExact(number.longValue());
|
||||
}
|
||||
|
||||
private static double decimal(Map<String, Object> values, SettingKey key) {
|
||||
Object value = required(values, key);
|
||||
if (!(value instanceof Number number) || !Double.isFinite(number.doubleValue())) {
|
||||
throw new IllegalArgumentException(key.key() + " must be a finite number.");
|
||||
}
|
||||
return number.doubleValue();
|
||||
}
|
||||
|
||||
private static Object required(Map<String, Object> values, SettingKey key) {
|
||||
Object value = values.get(key.key());
|
||||
if (value == null) throw new IllegalArgumentException("Missing " + key.key() + '.');
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String format(SettingKey key, SentinelSettings settings) {
|
||||
return switch (key) {
|
||||
case HORIZONTAL_SPEED_LIMIT -> decimal(settings.horizontalSpeedLimit(), 2);
|
||||
case BREACHES_TO_ALERT -> Integer.toString(settings.breachesToAlert());
|
||||
case EVIDENCE_WINDOW_SECONDS -> Integer.toString(settings.evidenceWindowSeconds());
|
||||
case ALERT_COOLDOWN_SECONDS -> Integer.toString(settings.alertCooldownSeconds());
|
||||
case MINIMUM_TPS -> decimal(settings.minimumTps(), 1);
|
||||
case EXEMPTION_GRACE_TICKS -> Integer.toString(settings.exemptionGraceTicks());
|
||||
};
|
||||
}
|
||||
|
||||
private static String decimal(double value, int minimumScale) {
|
||||
var decimal = BigDecimal.valueOf(value).stripTrailingZeros();
|
||||
if (decimal.scale() < minimumScale) decimal = decimal.setScale(minimumScale);
|
||||
return decimal.toPlainString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
horizontal-speed-limit: 0.80
|
||||
breaches-to-alert: 6
|
||||
evidence-window-seconds: 10
|
||||
alert-cooldown-seconds: 60
|
||||
minimum-tps: 18.0
|
||||
exemption-grace-ticks: 20
|
||||
@@ -0,0 +1,19 @@
|
||||
name: PurpurSentinel
|
||||
version: '${version}'
|
||||
main: games.dmg.purpursentinel.PurpurSentinelPlugin
|
||||
api-version: '26.3'
|
||||
description: Passive and explainable movement-pattern observation for operators.
|
||||
commands:
|
||||
sentinel:
|
||||
description: Inspect movement evidence or configure Sentinel.
|
||||
usage: /sentinel <inspect|config> ...
|
||||
permissions:
|
||||
sentinel.alerts:
|
||||
description: Receive passive movement evidence alerts.
|
||||
default: op
|
||||
sentinel.inspect:
|
||||
description: Inspect current movement evidence for an online player.
|
||||
default: op
|
||||
sentinel.config:
|
||||
description: Read and update Sentinel configuration.
|
||||
default: op
|
||||
@@ -0,0 +1,63 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.LayeredRegistryAccess;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.ReloadableServerResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import org.bukkit.craftbukkit.CraftRegistry;
|
||||
|
||||
/** Loads vanilla registries/tags/components using the same path as the server's own tests. */
|
||||
final class NativeRuntime {
|
||||
private static boolean initialized;
|
||||
|
||||
private NativeRuntime() {}
|
||||
|
||||
static synchronized void bootstrap() throws Exception {
|
||||
// Paper registries are process-global and reject loading a second time.
|
||||
if (initialized) return;
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
var flags = FeatureFlags.VANILLA_SET;
|
||||
var packs = ServerPacksSource.createVanillaTrustedRepository();
|
||||
MinecraftServer.configurePackRepository(packs, new WorldDataConfiguration(new DataPackConfig(
|
||||
FeatureFlags.REGISTRY.toNames(flags).stream().map(Identifier::getPath).toList(), List.of()), flags), true, false);
|
||||
try (var resources = new MultiPackResourceManager(PackType.SERVER_DATA, packs.openAllSelected())) {
|
||||
LayeredRegistryAccess<RegistryLayer> layers = RegistryLayer.createRegistryAccess();
|
||||
List<Registry.PendingTags<?>> tags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
List<HolderLookup.RegistryLookup<?>> lookups = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), tags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, lookups,
|
||||
RegistryDataLoader.WORLD_REGISTRIES, Util.backgroundExecutor()).join();
|
||||
layers = layers.replaceFrom(RegistryLayer.WORLD, world);
|
||||
RegistryAccess.Frozen dimensions = RegistryDataLoader.load(resources,
|
||||
Stream.concat(lookups.stream(), world.listRegistries()).toList(),
|
||||
RegistryDataLoader.DIMENSION_REGISTRIES, Util.backgroundExecutor()).join();
|
||||
layers = layers.replaceFrom(RegistryLayer.DIMENSIONS, dimensions);
|
||||
Class.forName(org.bukkit.Registry.class.getName());
|
||||
var datapack = ReloadableServerResources.loadResources(resources, layers, tags, flags,
|
||||
Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.ALL_PERMISSIONS,
|
||||
Util.backgroundExecutor(), Runnable::run).join();
|
||||
datapack.updateComponentsAndStaticRegistryTags();
|
||||
CraftRegistry.setMinecraftRegistry(layers.compositeAccess().freeze());
|
||||
}
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import io.papermc.paper.plugin.manager.NativeEvents;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.entity.Pose;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class PluginLifecycleTest {
|
||||
@TempDir File directory;
|
||||
|
||||
@BeforeAll static void bootstrap() throws Exception { NativeRuntime.bootstrap(); }
|
||||
|
||||
@Test @SuppressWarnings({"try", "unchecked", "rawtypes"})
|
||||
void packagedMetadataEnableNativeDispatchCommandsTickAndDisableFormOneConnectedPath() throws Exception {
|
||||
var server = mock(Server.class);
|
||||
when(server.isPrimaryThread()).thenReturn(true);
|
||||
when(server.getLogger()).thenReturn(java.util.logging.Logger.getLogger("SentinelServerTest"));
|
||||
when(server.getWarningState()).thenReturn(org.bukkit.Warning.WarningState.DEFAULT);
|
||||
when(server.getTPS()).thenReturn(new double[]{20, 20, 20});
|
||||
var currentTick = new java.util.concurrent.atomic.AtomicInteger(1);
|
||||
when(server.getCurrentTick()).thenAnswer(call -> currentTick.get());
|
||||
var scheduler = mock(BukkitScheduler.class);
|
||||
when(server.getScheduler()).thenReturn(scheduler);
|
||||
var manager = mock(PluginManager.class);
|
||||
when(server.getPluginManager()).thenReturn(manager);
|
||||
var events = new NativeEvents(server);
|
||||
var plugin = mock(PurpurSentinelPlugin.class);
|
||||
doCallRealMethod().when(plugin).onEnable();
|
||||
doCallRealMethod().when(plugin).onDisable();
|
||||
when(plugin.getServer()).thenReturn(server);
|
||||
when(plugin.isEnabled()).thenReturn(true);
|
||||
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getLogger("SentinelTest"));
|
||||
when(plugin.getDataFolder()).thenReturn(directory);
|
||||
try (var stream = getClass().getResourceAsStream("/plugin.yml")) {
|
||||
var description = new PluginDescriptionFile(stream);
|
||||
assertEquals("PurpurSentinel", description.getName());
|
||||
assertEquals("26.3", description.getAPIVersion());
|
||||
assertEquals(3, description.getPermissions().size());
|
||||
when(plugin.getDescription()).thenReturn(description);
|
||||
when(plugin.getPluginMeta()).thenReturn(description);
|
||||
}
|
||||
var constructor = PluginCommand.class.getDeclaredConstructor(String.class, org.bukkit.plugin.Plugin.class);
|
||||
constructor.setAccessible(true);
|
||||
var command = constructor.newInstance("sentinel", plugin);
|
||||
when(plugin.getCommand("sentinel")).thenReturn(command);
|
||||
doAnswer(call -> { events.register(call.getArgument(0), plugin); return null; })
|
||||
.when(manager).registerEvents(any(), eq(plugin));
|
||||
var tick = new AtomicReference<Runnable>();
|
||||
var task = mock(BukkitTask.class);
|
||||
when(scheduler.runTaskTimer(eq(plugin), any(Runnable.class), eq(1L), eq(1L))).thenAnswer(call -> {
|
||||
tick.set(call.getArgument(1)); return task;
|
||||
});
|
||||
|
||||
var world = mock(World.class);
|
||||
when(world.getUID()).thenReturn(UUID.randomUUID());
|
||||
when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true);
|
||||
when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(mock(org.bukkit.block.Block.class, invocation -> {
|
||||
if (invocation.getMethod().getName().equals("getType")) return org.bukkit.Material.AIR;
|
||||
if (invocation.getMethod().getName().equals("isLiquid")) return false;
|
||||
return RETURNS_DEFAULTS.answer(invocation);
|
||||
}));
|
||||
var subject = mock(Player.class);
|
||||
var operator = mock(Player.class);
|
||||
when(subject.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(subject.getName()).thenReturn("Alex");
|
||||
when(subject.isOnline()).thenReturn(true);
|
||||
when(subject.getGameMode()).thenReturn(GameMode.SURVIVAL);
|
||||
when(subject.getPose()).thenReturn(Pose.STANDING);
|
||||
when(operator.hasPermission("sentinel.alerts")).thenReturn(true);
|
||||
when(operator.hasPermission("sentinel.inspect")).thenReturn(true);
|
||||
when(server.getPlayer(subject.getUniqueId())).thenReturn(subject);
|
||||
doReturn((Collection) List.of(subject, operator)).when(server).getOnlinePlayers();
|
||||
|
||||
try (var platform = mockStatic(Bukkit.class)) {
|
||||
platform.when(Bukkit::getServer).thenReturn(server);
|
||||
platform.when(Bukkit::getPluginManager).thenReturn(manager);
|
||||
platform.when(Bukkit::getCurrentTick).thenAnswer(call -> currentTick.get());
|
||||
plugin.onEnable();
|
||||
assertNotNull(tick.get());
|
||||
assertInstanceOf(SentinelCommand.class, command.getExecutor());
|
||||
assertSame(command.getExecutor(), command.getTabCompleter());
|
||||
assertTrue(Files.readString(directory.toPath().resolve("config.yml")).contains("breaches-to-alert: 6"));
|
||||
for (int sample = 1; sample <= 6; sample++) {
|
||||
currentTick.set(sample);
|
||||
events.call(new PlayerMoveEvent(subject, new Location(world, 0, 64, 0), new Location(world, 1, 64, 0)));
|
||||
currentTick.incrementAndGet();
|
||||
tick.get().run();
|
||||
}
|
||||
verify(operator).sendMessage(argThat((String message) -> message.contains("6 movement breaches")));
|
||||
assertTrue(command.execute(operator, "sentinel", new String[]{"inspect", "Alex"}));
|
||||
verify(operator).sendMessage(argThat((String message) -> message.startsWith("Alex: 6 breaches")));
|
||||
assertEquals(List.of("inspect"), command.tabComplete(operator, "sentinel", new String[]{"in"}));
|
||||
|
||||
Field monitorField = PurpurSentinelPlugin.class.getDeclaredField("monitor");
|
||||
monitorField.setAccessible(true);
|
||||
var monitor = (MovementMonitor) monitorField.get(plugin);
|
||||
assertEquals(1, monitor.trackedPlayerCount());
|
||||
plugin.onDisable();
|
||||
verify(task).cancel();
|
||||
assertEquals(0, monitor.trackedPlayerCount());
|
||||
assertEquals(0, PlayerMoveEvent.getHandlerList().getRegisteredListeners().length);
|
||||
plugin.onDisable();
|
||||
} finally {
|
||||
HandlerList.unregisterAll(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void invalidStartupConfigurationRegistersNothing() throws Exception {
|
||||
Files.writeString(directory.toPath().resolve("config.yml"), "minimum-tps: bad\n");
|
||||
var server = mock(Server.class);
|
||||
var manager = mock(PluginManager.class);
|
||||
when(server.getPluginManager()).thenReturn(manager);
|
||||
var plugin = mock(PurpurSentinelPlugin.class);
|
||||
doCallRealMethod().when(plugin).onEnable();
|
||||
when(plugin.getServer()).thenReturn(server);
|
||||
when(plugin.getDataFolder()).thenReturn(directory);
|
||||
when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getLogger("SentinelTest"));
|
||||
plugin.onEnable();
|
||||
verify(manager).disablePlugin(plugin);
|
||||
verify(manager, never()).registerEvents(any(), any());
|
||||
verify(server, never()).getScheduler();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package io.papermc.paper.plugin.manager;
|
||||
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** Test-only access to Purpur's actual annotation registration and event dispatcher. */
|
||||
public final class NativeEvents {
|
||||
private final PaperEventManager events;
|
||||
public NativeEvents(Server server) { events = new PaperEventManager(server); }
|
||||
public void register(Listener listener, Plugin plugin) { events.registerEvents(listener, plugin); }
|
||||
public void call(Event event) { events.callEvent(event); }
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.stream.Stream;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Pose;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
class BukkitMovementListenerTest {
|
||||
private static final SentinelSettings SETTINGS = new SentinelSettings(0.8, 3, 10, 60, 18, 20);
|
||||
|
||||
@Test void eligibleNativeMovementFeedsOneTickSampleWithoutMutatingTheEvent() {
|
||||
var fixture = fixture();
|
||||
var event = move(fixture.player, fixture.world, 0, 1, false);
|
||||
fixture.listener.onMove(event);
|
||||
fixture.monitor.finishBefore(2, 100_000_000L);
|
||||
assertEquals(1, fixture.monitor.inspect(fixture.player.getUniqueId(), 100_000_000L).orElseThrow().breachCount());
|
||||
assertFalse(event.isCancelled());
|
||||
assertEquals(1, event.getTo().getX());
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}") @MethodSource("directExclusions")
|
||||
void directPlayerStateAndTpsExclusionsStartGrace(String name, java.util.function.Consumer<Fixture> arrange) {
|
||||
var fixture = fixture();
|
||||
arrange.accept(fixture);
|
||||
fixture.listener.onMove(move(fixture.player, fixture.world, 0, 2, false));
|
||||
fixture.monitor.finishBefore(2, 100_000_000L);
|
||||
assertTrue(fixture.monitor.inspect(fixture.player.getUniqueId(), 100_000_000L).isEmpty(), name);
|
||||
}
|
||||
|
||||
@Test void lifecycleVelocityQuitAndCancelledMovementArePassiveExemptions() {
|
||||
var fixture = fixture();
|
||||
fixture.listener.onMove(move(fixture.player, fixture.world, 0, 2, true));
|
||||
fixture.monitor.finishBefore(2, 100_000_000L);
|
||||
assertTrue(fixture.monitor.inspect(fixture.player.getUniqueId(), 100_000_000L).isEmpty());
|
||||
|
||||
fixture.listener.onVelocity(new org.bukkit.event.player.PlayerVelocityEvent(fixture.player, new org.bukkit.util.Vector(1, 0, 0)));
|
||||
fixture.listener.onQuit(new org.bukkit.event.player.PlayerQuitEvent(fixture.player, "bye"));
|
||||
assertEquals(0, fixture.monitor.trackedPlayerCount());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> directExclusions() {
|
||||
return Stream.of(
|
||||
Arguments.of("creative", (java.util.function.Consumer<Fixture>) f -> when(f.player.getGameMode()).thenReturn(GameMode.CREATIVE)),
|
||||
Arguments.of("vehicle", (java.util.function.Consumer<Fixture>) f -> when(f.player.isInsideVehicle()).thenReturn(true)),
|
||||
Arguments.of("flying", (java.util.function.Consumer<Fixture>) f -> when(f.player.isFlying()).thenReturn(true)),
|
||||
Arguments.of("gliding", (java.util.function.Consumer<Fixture>) f -> when(f.player.isGliding()).thenReturn(true)),
|
||||
Arguments.of("swimming", (java.util.function.Consumer<Fixture>) f -> when(f.player.isSwimming()).thenReturn(true)),
|
||||
Arguments.of("crawling", (java.util.function.Consumer<Fixture>) f -> when(f.player.getPose()).thenReturn(Pose.SWIMMING)),
|
||||
Arguments.of("climbing", (java.util.function.Consumer<Fixture>) f -> when(f.player.isClimbing()).thenReturn(true)),
|
||||
Arguments.of("riptide", (java.util.function.Consumer<Fixture>) f -> when(f.player.isRiptiding()).thenReturn(true)),
|
||||
Arguments.of("low tps", (java.util.function.Consumer<Fixture>) f -> when(f.server.getTPS()).thenReturn(new double[]{17.9, 20, 20})));
|
||||
}
|
||||
|
||||
private static Fixture fixture() {
|
||||
var server = mock(Server.class);
|
||||
when(server.getCurrentTick()).thenReturn(1);
|
||||
when(server.getTPS()).thenReturn(new double[]{20, 20, 20});
|
||||
var world = mock(World.class);
|
||||
when(world.getUID()).thenReturn(UUID.randomUUID());
|
||||
when(world.isChunkLoaded(anyInt(), anyInt())).thenReturn(true);
|
||||
when(world.getBlockAt(anyInt(), anyInt(), anyInt())).thenReturn(mock(org.bukkit.block.Block.class, invocation -> {
|
||||
if (invocation.getMethod().getName().equals("getType")) return org.bukkit.Material.AIR;
|
||||
if (invocation.getMethod().getName().equals("isLiquid")) return false;
|
||||
return RETURNS_DEFAULTS.answer(invocation);
|
||||
}));
|
||||
var player = mock(Player.class);
|
||||
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
when(player.getGameMode()).thenReturn(GameMode.SURVIVAL);
|
||||
when(player.getPose()).thenReturn(Pose.STANDING);
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var clock = new AtomicLong(50_000_000L);
|
||||
var listener = new BukkitMovementListener(server, monitor, () -> SETTINGS, clock::get, (from, to) -> true);
|
||||
return new Fixture(server, world, player, monitor, listener);
|
||||
}
|
||||
|
||||
private static PlayerMoveEvent move(Player player, World world, double from, double to, boolean cancelled) {
|
||||
var event = new PlayerMoveEvent(player, new Location(world, from, 64, 0), new Location(world, to, 64, 0));
|
||||
event.setCancelled(cancelled);
|
||||
return event;
|
||||
}
|
||||
|
||||
private record Fixture(Server server, World world, Player player, MovementMonitor monitor, BukkitMovementListener listener) {}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarFile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
class DistributionTest {
|
||||
@Test void shipsOnlyTheVersionedJava25PluginWithDeclaredCommandsPermissionsAndConfiguration() throws Exception {
|
||||
var path = Path.of(System.getProperty("distribution.jar"));
|
||||
String version = System.getProperty("distribution.version");
|
||||
assertEquals("purpur-sentinel-" + version + ".jar", path.getFileName().toString());
|
||||
try (var jar = new JarFile(path.toFile())) {
|
||||
Map<String, Object> metadata = new Yaml().load(jar.getInputStream(jar.getEntry("plugin.yml")));
|
||||
assertEquals("PurpurSentinel", metadata.get("name"));
|
||||
assertEquals(version, metadata.get("version"));
|
||||
assertEquals("games.dmg.purpursentinel.PurpurSentinelPlugin", metadata.get("main"));
|
||||
assertEquals("26.3", metadata.get("api-version"));
|
||||
assertEquals(1, ((Map<?, ?>) metadata.get("commands")).size());
|
||||
var permissions = (Map<?, ?>) metadata.get("permissions");
|
||||
assertEquals(java.util.Set.of("sentinel.alerts", "sentinel.inspect", "sentinel.config"), permissions.keySet());
|
||||
for (Object value : permissions.values()) assertEquals("op", ((Map<?, ?>) value).get("default"));
|
||||
assertNull(metadata.get("depend"));
|
||||
assertNull(metadata.get("softdepend"));
|
||||
assertNotNull(jar.getEntry("config.yml"));
|
||||
assertTrue(new String(jar.getInputStream(jar.getEntry("config.yml")).readAllBytes())
|
||||
.contains("horizontal-speed-limit: 0.80"));
|
||||
var entry = jar.getEntry("games/dmg/purpursentinel/PurpurSentinelPlugin.class");
|
||||
assertNotNull(entry);
|
||||
try (var bytes = new DataInputStream(jar.getInputStream(entry))) {
|
||||
assertEquals(0xcafebabe, bytes.readInt());
|
||||
bytes.readUnsignedShort();
|
||||
assertEquals(69, bytes.readUnsignedShort());
|
||||
}
|
||||
assertTrue(jar.stream().filter(candidate -> candidate.getName().endsWith(".class"))
|
||||
.allMatch(candidate -> candidate.getName().startsWith("games/dmg/purpursentinel/")
|
||||
&& !candidate.getName().endsWith("Test.class")));
|
||||
assertTrue(jar.stream().noneMatch(candidate -> candidate.getName().contains("nativeTest")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MovementDetectorTest {
|
||||
private static final SentinelSettings SETTINGS = new SentinelSettings(0.80, 3, 10, 60, 18.0, 20);
|
||||
|
||||
@Test void repeatedEligibleTicksAlertOnceAndExposeBoundedEvidence() {
|
||||
var detector = new MovementDetector();
|
||||
var player = UUID.randomUUID();
|
||||
|
||||
assertTrue(detector.observe(player, sample(1, 0.90), SETTINGS).isEmpty());
|
||||
assertTrue(detector.observe(player, sample(2, 0.95), SETTINGS).isEmpty());
|
||||
var alert = detector.observe(player, sample(3, 1.00), SETTINGS).orElseThrow();
|
||||
|
||||
assertEquals(player, alert.playerId());
|
||||
assertEquals(3, alert.breachCount());
|
||||
assertEquals(1.00, alert.peakSpeed(), 1e-9);
|
||||
assertEquals(0.80, alert.capturedLimit(), 1e-9);
|
||||
var inspection = detector.inspect(player, 150_000_000L).orElseThrow();
|
||||
assertEquals(3, inspection.breachCount());
|
||||
assertEquals(1.00, inspection.peakSpeed(), 1e-9);
|
||||
assertEquals(0.80, inspection.capturedLimit(), 1e-9);
|
||||
assertTrue(detector.observe(player, sample(4, 1.10), SETTINGS).isEmpty(), "cooldown suppresses repeats");
|
||||
}
|
||||
|
||||
@Test void isolatedLegalAndExpiredBreachesNeverAlert() {
|
||||
var detector = new MovementDetector();
|
||||
var player = UUID.randomUUID();
|
||||
assertTrue(detector.observe(player, sample(1, 0.40), SETTINGS).isEmpty());
|
||||
assertTrue(detector.observe(player, sample(2, 0.81), SETTINGS).isEmpty());
|
||||
assertTrue(detector.observe(player, sample(203, 0.82), SETTINGS).isEmpty());
|
||||
assertEquals(1, detector.inspect(player, 10_100_000_000L).orElseThrow().breachCount());
|
||||
}
|
||||
|
||||
@Test void exclusionsStartInclusiveGraceAndNeverCreateEvidence() {
|
||||
for (var reason : ExclusionReason.values()) {
|
||||
if (reason == ExclusionReason.NONE) continue;
|
||||
var detector = new MovementDetector();
|
||||
var player = UUID.randomUUID();
|
||||
detector.observe(player, new MovementSample(1, 50_000_000L, true,
|
||||
reason == ExclusionReason.CANCELLED, 2.0, reason), SETTINGS);
|
||||
for (int tick = 2; tick <= 21; tick++) {
|
||||
assertTrue(detector.observe(player, sample(tick, 2.0), SETTINGS).isEmpty(), reason.name());
|
||||
}
|
||||
assertTrue(detector.inspect(player, 1_050_000_000L).isEmpty());
|
||||
assertTrue(detector.observe(player, sample(22, 2.0), SETTINGS).isEmpty());
|
||||
assertEquals(1, detector.evidenceCount(player));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void cleanupRetainsExemptionGraceUntilItsFinalTick() {
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var player = UUID.randomUUID();
|
||||
var world = UUID.randomUUID();
|
||||
monitor.exempt(player, 10, 500_000_000L, ExclusionReason.VELOCITY, SETTINGS);
|
||||
|
||||
monitor.finishBefore(11, 550_000_000L);
|
||||
assertEquals(1, monitor.trackedPlayerCount());
|
||||
monitor.finishBefore(30, 1_500_000_000L);
|
||||
assertEquals(1, monitor.trackedPlayerCount());
|
||||
monitor.record(player, new MovementFrame(30, 1_500_000_000L, world, world,
|
||||
0, 0, 2, 0, ExclusionReason.NONE), SETTINGS);
|
||||
|
||||
monitor.finishBefore(31, 1_550_000_000L);
|
||||
assertTrue(monitor.inspect(player, 1_550_000_000L).isEmpty());
|
||||
assertEquals(0, monitor.trackedPlayerCount());
|
||||
}
|
||||
|
||||
@Test void evidenceIsBoundedAndLifecycleCleanupIsExact() {
|
||||
var detector = new MovementDetector();
|
||||
var player = UUID.randomUUID();
|
||||
var longWindow = new SentinelSettings(0.40, 40, 60, 60, 18.0, 20);
|
||||
for (int tick = 1; tick <= 1_250; tick++) {
|
||||
detector.observe(player, new MovementSample(tick, tick * 1_000_000L, true, false, 1.0, ExclusionReason.NONE), longWindow);
|
||||
}
|
||||
assertEquals(MovementDetector.MAX_EVIDENCE_PER_PLAYER, detector.evidenceCount(player));
|
||||
detector.forget(player);
|
||||
assertEquals(0, detector.trackedPlayerCount());
|
||||
detector.observe(player, sample(2_000, 1.0), SETTINGS);
|
||||
detector.clear();
|
||||
assertEquals(0, detector.trackedPlayerCount());
|
||||
}
|
||||
|
||||
@Test void thresholdLimitWindowAndCooldownAreCapturedByEachFutureDecision() {
|
||||
var detector = new MovementDetector();
|
||||
var player = UUID.randomUUID();
|
||||
var old = new SentinelSettings(0.80, 3, 60, 60, 18.0, 20);
|
||||
var updated = new SentinelSettings(0.60, 4, 2, 5, 18.0, 20);
|
||||
detector.observe(player, sample(1, 0.90), old);
|
||||
detector.observe(player, sample(2, 0.95), old);
|
||||
assertTrue(detector.observe(player, sample(3, 0.70), updated).isEmpty());
|
||||
var alert = detector.observe(player, sample(4, 0.75), updated).orElseThrow();
|
||||
assertEquals(4, alert.breachCount());
|
||||
assertEquals(0.80, alert.capturedLimit(), 1e-9, "peak evidence keeps its captured limit");
|
||||
assertTrue(detector.observe(player, sample(50, 0.90), updated).isEmpty());
|
||||
assertTrue(detector.observe(player, new MovementSample(105, 5_250_000_000L, true, false, 0.90, ExclusionReason.NONE), updated).isPresent());
|
||||
}
|
||||
|
||||
private static MovementSample sample(int tick, double distance) {
|
||||
return new MovementSample(tick, tick * 50_000_000L, true, false, distance, ExclusionReason.NONE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class MovementMonitorTest {
|
||||
private static final UUID WORLD = UUID.randomUUID();
|
||||
private static final SentinelSettings SETTINGS = new SentinelSettings(0.80, 3, 10, 60, 18.0, 20);
|
||||
|
||||
@Test void oneSamplePerTickUsesMaximumAnchorDistanceInsteadOfEventCountOrSum() {
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var player = UUID.randomUUID();
|
||||
monitor.record(player, frame(1, 0, 0, 0.4, 0), SETTINGS);
|
||||
monitor.record(player, frame(1, 0.4, 0, 0.9, 0), SETTINGS);
|
||||
monitor.record(player, frame(1, 0.4, 0, 0.9, 0), SETTINGS); // duplicate event
|
||||
monitor.finishBefore(2, 100_000_000L);
|
||||
|
||||
var snapshot = monitor.inspect(player, 100_000_000L).orElseThrow();
|
||||
assertEquals(1, snapshot.breachCount());
|
||||
assertEquals(0.9, snapshot.peakSpeed(), 1e-9);
|
||||
}
|
||||
|
||||
@Test void outAndBackRetainsFurthestPointWhileBrokenChainsExcludeWholeTick() {
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var player = UUID.randomUUID();
|
||||
monitor.record(player, frame(1, 0, 0, 1.0, 0), SETTINGS);
|
||||
monitor.record(player, frame(1, 1.0, 0, 0.1, 0), SETTINGS);
|
||||
monitor.finishBefore(2, 100_000_000L);
|
||||
assertEquals(1.0, monitor.inspect(player, 100_000_000L).orElseThrow().peakSpeed(), 1e-9);
|
||||
|
||||
monitor.record(player, frame(2, 0.1, 0, 1.0, 0), SETTINGS);
|
||||
monitor.record(player, frame(2, 3.0, 0, 4.0, 0), SETTINGS);
|
||||
monitor.finishBefore(3, 150_000_000L);
|
||||
assertEquals(1, monitor.inspect(player, 150_000_000L).orElseThrow().breachCount());
|
||||
}
|
||||
|
||||
@Test void excludedOrCrossWorldEventInvalidatesTheWholeTick() {
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var player = UUID.randomUUID();
|
||||
monitor.record(player, frame(1, 0, 0, 1.0, 0), SETTINGS);
|
||||
monitor.record(player, frame(1, 1.0, 0, 2.0, 0).withReason(ExclusionReason.ENVIRONMENT), SETTINGS);
|
||||
assertEquals(List.of(), monitor.finishBefore(2, 100_000_000L));
|
||||
assertTrue(monitor.inspect(player, 100_000_000L).isEmpty());
|
||||
|
||||
monitor.record(player, new MovementFrame(30, 1_500_000_000L, WORLD, UUID.randomUUID(), 0, 0, 1, 0, ExclusionReason.NONE), SETTINGS);
|
||||
monitor.finishBefore(31, 1_550_000_000L);
|
||||
assertTrue(monitor.inspect(player, 1_550_000_000L).isEmpty());
|
||||
}
|
||||
|
||||
private static MovementFrame frame(int tick, double fromX, double fromZ, double toX, double toZ) {
|
||||
return new MovementFrame(tick, tick * 50_000_000L, WORLD, WORLD, fromX, fromZ, toX, toZ, ExclusionReason.NONE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class PrivacyBoundaryTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test void observationAndInspectionNeverPersistPlayerIdentityOrEvidence() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(file);
|
||||
var service = SettingsService.load(new AtomicYamlSettingsStore(file));
|
||||
byte[] before = Files.readAllBytes(file);
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var player = UUID.fromString("12345678-1234-1234-1234-123456789abc");
|
||||
for (int tick = 1; tick <= 6; tick++) {
|
||||
var world = UUID.randomUUID();
|
||||
monitor.record(player, new MovementFrame(tick, tick * 50_000_000L, world, world,
|
||||
120.25, -45.5, 121.25, -45.5, ExclusionReason.NONE), service.current());
|
||||
monitor.finishBefore(tick + 1, tick * 50_000_000L + 1);
|
||||
}
|
||||
assertTrue(monitor.inspect(player, 400_000_000L).isPresent());
|
||||
assertArrayEquals(before, Files.readAllBytes(file));
|
||||
assertEquals(java.util.Set.of("config.yml"), Files.list(directory)
|
||||
.map(path -> path.getFileName().toString()).collect(java.util.stream.Collectors.toSet()));
|
||||
String disk = Files.readString(file);
|
||||
assertFalse(disk.contains(player.toString()));
|
||||
assertFalse(disk.contains("120.25"));
|
||||
assertFalse(disk.contains("-45.5"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SentinelAlertsTest {
|
||||
@Test @SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void sendsExplainableAlertsOnlyToOnlinePermittedPlayersAndNeverConsole() {
|
||||
var server = mock(Server.class);
|
||||
var subject = mock(Player.class);
|
||||
var operator = mock(Player.class);
|
||||
var denied = mock(Player.class);
|
||||
var id = UUID.randomUUID();
|
||||
when(server.getPlayer(id)).thenReturn(subject);
|
||||
when(subject.isOnline()).thenReturn(true);
|
||||
when(subject.getName()).thenReturn("Alex");
|
||||
when(operator.hasPermission("sentinel.alerts")).thenReturn(true);
|
||||
doReturn((java.util.Collection) List.of(operator, denied)).when(server).getOnlinePlayers();
|
||||
|
||||
new SentinelAlerts(server).send(new AlertDecision(id, 6, 1.03, 0.80));
|
||||
|
||||
verify(operator).sendMessage(argThat((String message) -> message.contains("6 movement breaches")
|
||||
&& message.contains("1.03") && message.contains("0.80") && !message.toLowerCase().contains("cheat")));
|
||||
verify(denied, never()).sendMessage(anyString());
|
||||
verify(server, never()).getConsoleSender();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SentinelCommandTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test void inspectRechecksPermissionAndReportsOnlyBoundedSummary() throws Exception {
|
||||
var fixture = fixture();
|
||||
var target = online(fixture.server, "Alex");
|
||||
var observer = mock(CommandSender.class);
|
||||
when(observer.hasPermission("sentinel.inspect")).thenReturn(true);
|
||||
addEvidence(fixture.monitor, target.getUniqueId());
|
||||
|
||||
assertTrue(fixture.command.onCommand(observer, mock(Command.class), "sentinel", new String[]{"inspect", "aLeX"}));
|
||||
verify(observer).sendMessage(argThat((String message) -> message.contains("3 breaches")
|
||||
&& message.contains("peak 1.00") && message.contains("limit 0.80")
|
||||
&& !message.matches(".*-?[0-9]+\\.[0-9]+, *-?[0-9]+\\.[0-9]+.*")));
|
||||
|
||||
var denied = mock(CommandSender.class);
|
||||
assertTrue(fixture.command.onCommand(denied, mock(Command.class), "sentinel", new String[]{"inspect", "Alex"}));
|
||||
verify(denied).sendMessage("You do not have permission to inspect Sentinel evidence.");
|
||||
}
|
||||
|
||||
@Test void inspectDistinguishesUnknownOfflineAndNoCurrentEvidenceWithoutMutation() throws Exception {
|
||||
var fixture = fixture();
|
||||
var sender = permitted("sentinel.inspect");
|
||||
var online = online(fixture.server, "Online");
|
||||
assertTrue(fixture.command.onCommand(sender, mock(Command.class), "sentinel", new String[]{"inspect", "Online"}));
|
||||
verify(sender).sendMessage(contains("No current evidence"));
|
||||
|
||||
var offline = mock(OfflinePlayer.class);
|
||||
when(fixture.server.getOfflinePlayerIfCached("Past")).thenReturn(offline);
|
||||
assertTrue(fixture.command.onCommand(sender, mock(Command.class), "sentinel", new String[]{"inspect", "Past"}));
|
||||
verify(sender).sendMessage("Past is offline; Sentinel retains no offline evidence.");
|
||||
|
||||
assertTrue(fixture.command.onCommand(sender, mock(Command.class), "sentinel", new String[]{"inspect", "Missing"}));
|
||||
verify(sender).sendMessage("Unknown player: Missing.");
|
||||
verify(online, never()).teleport(any(org.bukkit.Location.class));
|
||||
}
|
||||
|
||||
@Test void configReadsAndDurablyUpdatesBeforeFutureDetection() throws Exception {
|
||||
var fixture = fixture();
|
||||
var sender = permitted("sentinel.config");
|
||||
assertTrue(fixture.command.onCommand(sender, mock(Command.class), "sentinel",
|
||||
new String[]{"config", "horizontal-speed-limit", "0.60"}));
|
||||
assertEquals(0.60, fixture.settings.current().horizontalSpeedLimit(), 1e-9);
|
||||
assertEquals(0.60, SettingsService.load(new AtomicYamlSettingsStore(fixture.file)).current().horizontalSpeedLimit(), 1e-9);
|
||||
verify(sender).sendMessage("horizontal-speed-limit updated to 0.60.");
|
||||
|
||||
var player = UUID.randomUUID();
|
||||
fixture.monitor.record(player, new MovementFrame(1, 50_000_000L, UUID.randomUUID(), UUID.randomUUID(), 0, 0, 1, 0, ExclusionReason.NONE), fixture.settings.current());
|
||||
assertEquals(0, fixture.monitor.trackedPlayerCount(), "cross-world input remains excluded after config mutation");
|
||||
}
|
||||
|
||||
@Test void registeredStyleAutocompleteIsPermissionAwarePrefixFilteredStableAndNonMutating() throws Exception {
|
||||
var fixture = fixture();
|
||||
online(fixture.server, "Zed");
|
||||
online(fixture.server, "alice");
|
||||
var both = mock(CommandSender.class);
|
||||
when(both.hasPermission("sentinel.inspect")).thenReturn(true);
|
||||
when(both.hasPermission("sentinel.config")).thenReturn(true);
|
||||
var command = mock(Command.class);
|
||||
|
||||
assertEquals(List.of("config", "inspect"), fixture.command.onTabComplete(both, command, "sentinel", new String[]{""}));
|
||||
assertEquals(List.of("inspect"), fixture.command.onTabComplete(both, command, "sentinel", new String[]{"IN"}));
|
||||
assertEquals(List.of("alice", "Zed"), fixture.command.onTabComplete(both, command, "sentinel", new String[]{"inspect", ""}));
|
||||
assertEquals(List.of("horizontal-speed-limit"), fixture.command.onTabComplete(both, command, "sentinel", new String[]{"config", "hor"}));
|
||||
assertEquals(List.of("0.40", "0.80", "5.00"), fixture.command.onTabComplete(both, command, "sentinel",
|
||||
new String[]{"config", "horizontal-speed-limit", ""}));
|
||||
assertEquals(List.of(), fixture.command.onTabComplete(both, command, "sentinel", new String[]{"inspect", "alice", "extra"}));
|
||||
assertEquals(List.of(), fixture.command.onTabComplete(mock(CommandSender.class), command, "sentinel", new String[]{""}));
|
||||
}
|
||||
|
||||
@Test void unsupportedMissingExtraInvalidAndDeniedConfigurationNeverMutate() throws Exception {
|
||||
var fixture = fixture();
|
||||
var original = fixture.settings.current();
|
||||
var sender = permitted("sentinel.config");
|
||||
for (String[] args : List.of(new String[0], new String[]{"other"}, new String[]{"config"},
|
||||
new String[]{"config", "missing"}, new String[]{"config", "breaches-to-alert", "2"},
|
||||
new String[]{"config", "breaches-to-alert", "8", "extra"})) {
|
||||
assertTrue(fixture.command.onCommand(sender, mock(Command.class), "sentinel", args));
|
||||
}
|
||||
var denied = mock(CommandSender.class);
|
||||
fixture.command.onCommand(denied, mock(Command.class), "sentinel", new String[]{"config", "breaches-to-alert", "8"});
|
||||
assertEquals(original, fixture.settings.current());
|
||||
}
|
||||
|
||||
private Fixture fixture() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(file);
|
||||
var settings = SettingsService.load(new AtomicYamlSettingsStore(file));
|
||||
var server = mock(Server.class);
|
||||
var monitor = new MovementMonitor(new MovementDetector());
|
||||
var clock = new AtomicLong(150_000_000L);
|
||||
return new Fixture(file, server, settings, monitor, new SentinelCommand(server, monitor, settings, clock::get));
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static Player online(Server server, String name) {
|
||||
var existing = new java.util.ArrayList<Player>();
|
||||
for (Player player : server.getOnlinePlayers()) existing.add(player);
|
||||
var player = mock(Player.class);
|
||||
when(player.getName()).thenReturn(name);
|
||||
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
|
||||
existing.add(player);
|
||||
doReturn((java.util.Collection) existing).when(server).getOnlinePlayers();
|
||||
return player;
|
||||
}
|
||||
|
||||
private static CommandSender permitted(String permission) {
|
||||
var sender = mock(CommandSender.class);
|
||||
when(sender.hasPermission(permission)).thenReturn(true);
|
||||
return sender;
|
||||
}
|
||||
|
||||
private static void addEvidence(MovementMonitor monitor, UUID player) {
|
||||
var settings = new SentinelSettings(0.8, 3, 10, 60, 18, 20);
|
||||
for (int tick = 1; tick <= 3; tick++) {
|
||||
var world = UUID.randomUUID();
|
||||
monitor.record(player, new MovementFrame(tick, tick * 50_000_000L, world, world, 0, 0, tick == 3 ? 1 : .9, 0, ExclusionReason.NONE), settings);
|
||||
monitor.finishBefore(tick + 1, tick * 50_000_000L + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private record Fixture(Path file, Server server, SettingsService settings, MovementMonitor monitor, SentinelCommand command) {}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package games.dmg.purpursentinel;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SettingsServiceTest {
|
||||
@TempDir Path directory;
|
||||
|
||||
@Test void validUpdatePersistsBeforePublicationAndPreservesUnrelatedYaml() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
Files.writeString(file, "horizontal-speed-limit: 0.8\nbreaches-to-alert: 6\nevidence-window-seconds: 10\nalert-cooldown-seconds: 60\nminimum-tps: 18.0\nexemption-grace-ticks: 20\nunrelated: keep-me\n");
|
||||
var service = SettingsService.load(new AtomicYamlSettingsStore(file));
|
||||
|
||||
assertEquals("0.60", service.update(SettingKey.HORIZONTAL_SPEED_LIMIT, "0.60"));
|
||||
assertEquals(0.60, service.current().horizontalSpeedLimit(), 1e-9);
|
||||
String saved = Files.readString(file);
|
||||
assertTrue(saved.contains("horizontal-speed-limit: 0.6"));
|
||||
assertTrue(saved.contains("unrelated: keep-me"));
|
||||
}
|
||||
|
||||
@Test void invalidAndFailedWritesKeepPriorEffectiveAndDiskValues() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(file);
|
||||
var initialBytes = Files.readAllBytes(file);
|
||||
var failing = new SettingsPersistence() {
|
||||
private final AtomicYamlSettingsStore delegate = new AtomicYamlSettingsStore(file);
|
||||
@Override public SettingsDocument load() throws IOException { return delegate.load(); }
|
||||
@Override public void save(SettingsDocument document) throws IOException { throw new IOException("fixture failure"); }
|
||||
};
|
||||
var service = SettingsService.load(failing);
|
||||
assertThrows(IllegalArgumentException.class, () -> service.update(SettingKey.BREACHES_TO_ALERT, "2"));
|
||||
assertThrows(IOException.class, () -> service.update(SettingKey.BREACHES_TO_ALERT, "8"));
|
||||
assertEquals(6, service.current().breachesToAlert());
|
||||
assertArrayEquals(initialBytes, Files.readAllBytes(file));
|
||||
}
|
||||
|
||||
@Test void concurrentAcceptedUpdatesSerializeWithoutLosingEitherValue() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(file);
|
||||
var service = SettingsService.load(new AtomicYamlSettingsStore(file));
|
||||
var gate = new CountDownLatch(1);
|
||||
var first = Thread.ofPlatform().start(() -> update(service, gate, SettingKey.BREACHES_TO_ALERT, "8"));
|
||||
var second = Thread.ofPlatform().start(() -> update(service, gate, SettingKey.EVIDENCE_WINDOW_SECONDS, "12"));
|
||||
gate.countDown();
|
||||
first.join();
|
||||
second.join();
|
||||
assertEquals(8, service.current().breachesToAlert());
|
||||
assertEquals(12, service.current().evidenceWindowSeconds());
|
||||
var loaded = SettingsService.load(new AtomicYamlSettingsStore(file));
|
||||
assertEquals(service.current(), loaded.current());
|
||||
}
|
||||
|
||||
@Test void malformedStartupConfigurationFailsBeforeUse() throws Exception {
|
||||
var file = directory.resolve("config.yml");
|
||||
AtomicYamlSettingsStore.writeDefaults(file);
|
||||
Files.writeString(file, Files.readString(file).replace("minimum-tps: 18.0", "minimum-tps: NaN"));
|
||||
assertThrows(IllegalArgumentException.class, () -> SettingsService.load(new AtomicYamlSettingsStore(file)));
|
||||
}
|
||||
|
||||
private static void update(SettingsService service, CountDownLatch gate, SettingKey key, String value) {
|
||||
try {
|
||||
gate.await();
|
||||
service.update(key, value);
|
||||
} catch (Exception exception) {
|
||||
throw new AssertionError(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user