From 228de3d08f833c2bb33e5ed9a805542b7f3aad95 Mon Sep 17 00:00:00 2001 From: Dylan Garvis Date: Fri, 25 Sep 2026 02:42:05 -0400 Subject: [PATCH] feat(events): record Frost Nova burst outcomes --- .../dmg/fantasystick/FantasyStickPlugin.java | 2 + .../dmg/fantasystick/ability/FrostNova.java | 88 +++++++++++++++---- .../persistence/FrostNovaSettings.java | 5 +- .../session/EquipmentAdminCommand.java | 13 ++- .../dmg/fantasystick/FrostNovaNativeTest.java | 57 ++++++++++++ .../persistence/FrostNovaSettingsTest.java | 3 +- 6 files changed, 145 insertions(+), 23 deletions(-) diff --git a/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java b/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java index d4e478d..e5290ec 100644 --- a/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java +++ b/src/main/java/games/dmg/fantasystick/FantasyStickPlugin.java @@ -714,6 +714,7 @@ public final class FantasyStickPlugin extends JavaPlugin { eventCapture = new games.dmg.fantasystick.events.EventCaptureListener(eventLog, sessions, Clock.systemUTC()); eventCapture.excludeOwnedDamage(fireball::ownsAcceptedDamage); eventCapture.excludeOwnedDamage(guardianBond::ownsAcceptedRedirect); + eventCapture.excludeOwnedDamage(frostNova::ownsAcceptedDamage); downedEvents = new games.dmg.fantasystick.events.DownedEventBridge(eventLog::emit, Clock.systemUTC()); rareEvents = new games.dmg.fantasystick.events.RareEventBridge(eventLog::emit, Clock.systemUTC());rareShop.attachEvents(rareEvents); bookEvents = new games.dmg.fantasystick.events.BookEventBridge(eventLog::emit, Clock.systemUTC());books.attachEvents(bookEvents); @@ -725,6 +726,7 @@ public final class FantasyStickPlugin extends JavaPlugin { abilityEngine.enableCastEventsFor("purify"); abilityEngine.enableCastEventsFor("guardian_bond"); abilityEngine.enableCastEventsFor("rallying_cry"); + abilityEngine.enableCastEventsFor("frost_nova"); admin.attachAbilityConfigEvents(new games.dmg.fantasystick.events.AbilityConfigEventBridge(eventLog::emit, Clock.systemUTC())); passiveEvents = new games.dmg.fantasystick.events.PassiveEventBridge(eventLog::emit, Clock.systemUTC());books.attachPassiveEvents(passiveEvents);admin.attachPassiveEvents(passiveEvents); recoveryEvents = new games.dmg.fantasystick.events.RecoveryEventBridge(eventLog::emit, Clock.systemUTC());outOfCombatRecovery.attachEvents(recoveryEvents,record->record.passives().contains(games.dmg.fantasystick.passive.QuickerRegenerationI.ID)?quickerRegeneration.bonus():java.math.BigInteger.ZERO); diff --git a/src/main/java/games/dmg/fantasystick/ability/FrostNova.java b/src/main/java/games/dmg/fantasystick/ability/FrostNova.java index a2909ee..5b538b1 100644 --- a/src/main/java/games/dmg/fantasystick/ability/FrostNova.java +++ b/src/main/java/games/dmg/fantasystick/ability/FrostNova.java @@ -50,36 +50,61 @@ public final class FrostNova implements AbilityEffect, Listener, AutoCloseable { private static final class SlowLease implements AutoCloseable { final LivingEntity target; final PotionEffect previous; final PotionEffect applied; + final AbilityExecution execution; UUID application; final long started = System.nanoTime(); boolean owned; boolean closed; - SlowLease(LivingEntity target, PotionEffect applied) { + SlowLease(LivingEntity target, PotionEffect applied, AbilityExecution execution) { this.target = target; previous = target.getPotionEffect(PotionEffectType.SLOWNESS); this.applied = applied; + this.execution = execution; } - boolean apply() { owned = target.addPotionEffect(applied); return owned; } - @Override public void close() { + boolean apply() { + owned = target.addPotionEffect(applied); + if (owned) try { + var evidence = new LinkedHashMap(); + evidence.put("amplifier", applied.getAmplifier()); + evidence.put("duration_ticks", applied.getDuration()); + evidence.put("deadline", java.time.Instant.now().plusMillis(applied.getDuration() * 50L).toString()); + if (previous != null) { + evidence.put("replaced_amplifier", previous.getAmplifier()); + evidence.put("replaced_duration_ticks", previous.getDuration()); + } + application = execution.effectApplied("frost_nova_slowness", target, evidence); + } catch (RuntimeException ignored) { /* Auditing cannot refuse a native effect. */ } + return owned; + } + @Override public void close() { close("interrupted"); } + void close(String reason) { if (closed) return; closed = true; if (!owned) return; var current = target.getPotionEffect(PotionEffectType.SLOWNESS); long elapsed = Math.max(0, (System.nanoTime() - started) / 50_000_000L); int expected = (int) Math.max(0, (long) applied.getDuration() - elapsed); if (current == null || current.getAmplifier() != applied.getAmplifier() - || current.getDuration() > expected + 2) return; + || current.getDuration() > expected + 2) { + if (application != null) execution.effectEnded(application, "superseded"); + return; + } target.removePotionEffect(PotionEffectType.SLOWNESS); if (previous != null) { int remaining = (int) Math.max(0, (long) previous.getDuration() - elapsed); if (remaining > 0) target.addPotionEffect(previous.withDuration(remaining)); } + if (application != null) execution.effectEnded(application, reason); } } private final class LeaseGroup implements AutoCloseable { - final AbilityExecution execution; final List leases = new ArrayList<>(); boolean closed; + final AbilityExecution execution; final List leases = new ArrayList<>(); + String endReason = "interrupted"; boolean closed; LeaseGroup(AbilityExecution execution) { this.execution = execution; } @Override public void close() { if (closed) return; closed = true; active.remove(execution, this); - for (var lease : List.copyOf(leases)) lease.close(); leases.clear(); + for (var lease : List.copyOf(leases)) lease.close(endReason); leases.clear(); } } private static final class Attempt { - final AbilityExecution execution; final LivingEntity target; boolean accepted; - Attempt(AbilityExecution execution, LivingEntity target) { this.execution = execution; this.target = target; } + final AbilityExecution execution; final LivingEntity target; final double requested; final int ordinal; + boolean accepted; + Attempt(AbilityExecution execution, LivingEntity target, double requested, int ordinal) { + this.execution = execution; this.target = target; this.requested = requested; this.ordinal = ordinal; + } } private volatile Settings settings; @@ -133,28 +158,39 @@ public final class FrostNova implements AbilityEffect, Listener, AutoCloseable { var group = new LeaseGroup(execution); active.put(execution, group); execution.own(group); BigInteger exact = damage(captured.baseDamage(), execution.character().stats().get(Stat.INT)); double amount = exact.bitLength() > 1023 ? Double.MAX_VALUE : exact.doubleValue(); - int affected = 0; - for (var target : candidates(source, origin, captured.radius())) { + int affected = 0, accepted = 0; + var candidates = candidates(source, origin, captured.radius()); + for (var target : candidates) { if (affected == 64 || !execution.stillCurrent()) break; if (!eligible(execution, target, origin, captured.radius())) continue; var sourceDamage = DamageSource.builder(DamageType.FREEZE).withCausingEntity(source) .withDirectEntity(source).withDamageLocation(origin).build(); - var attempt = new Attempt(execution, target); damaging = attempt; + var attempt = new Attempt(execution, target, amount, affected + 1); damaging = attempt; try { execution.damage(target, amount, sourceDamage); } finally { if (damaging == attempt) damaging = null; } affected++; - if (!attempt.accepted || !execution.stillCurrent() || !eligible(execution, target, origin, captured.radius())) continue; + if (!attempt.accepted) continue; + accepted++; + if (!execution.stillCurrent() || !eligible(execution, target, origin, captured.radius())) continue; int ticks = Math.toIntExact(Math.max(1, (captured.slownessDuration().toNanos() + 49_999_999L) / 50_000_000L)); var lease = new SlowLease(target, new PotionEffect(PotionEffectType.SLOWNESS, ticks, - captured.slownessAmplifier(), false, true, true)); + captured.slownessAmplifier(), false, true, true), execution); if (lease.apply()) group.leases.add(lease); } try { particles.world(Particle.SNOWFLAKE, origin, 32, captured.radius() / 2, captured.radius() / 2, captured.radius() / 2, 0.01); } catch (RuntimeException ignored) { } + var result = new LinkedHashMap(); + result.put("candidate_count", candidates.size()); result.put("attempt_count", affected); + result.put("accepted_count", accepted); result.put("slowness_count", group.leases.size()); + result.put("radius", captured.radius()); result.put("requested_amount", amount); + result.put("burst_location", locationData(origin)); + execution.resolve(accepted > 0 ? "hit" : "miss", result); if (group.leases.isEmpty()) execution.finish(); - else execution.later(captured.slownessDuration(), execution::finish); + else execution.later(captured.slownessDuration(), () -> { + group.endReason = "expired"; execution.finish(); + }); } private List candidates(Player source, Location origin, double radius) { @@ -188,13 +224,33 @@ public final class FrostNova implements AbilityEffect, Listener, AutoCloseable { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void acceptedDamage(EntityDamageEvent event) { var attempt = damaging; - if (attempt == null || attempt.accepted || event.getEntity() != attempt.target - || event.getCause() != EntityDamageEvent.DamageCause.FREEZE + if (!ownsAcceptedDamage(event) || attempt.accepted || event.getFinalDamage() <= 0 || !Double.isFinite(event.getFinalDamage())) return; attempt.accepted = true; + attempt.execution.acceptedDamage(attempt.target, attempt.requested, event.getFinalDamage(), + attempt.execution.input().player(), Map.of("damage_kind", "owned_area_burst", "ordinal", attempt.ordinal)); attempt.execution.report(AbilityReport.Type.DAMAGE, attempt.target, BigDecimal.valueOf(event.getFinalDamage())); } + /** The per-target native hit belongs to this cast, not the generic damage observer. */ + public boolean ownsAcceptedDamage(EntityDamageEvent event) { + var attempt = damaging; + if (attempt == null || event.getEntity() != attempt.target + || event.getCause() != EntityDamageEvent.DamageCause.FREEZE) return false; + var source = attempt.execution.input().player(); + var causing = event.getDamageSource().getCausingEntity(); + var direct = event.getDamageSource().getDirectEntity(); + return (causing == null || causing == source) && (direct == null || direct == source); + } + + private static Map locationData(Location origin) { + var world = origin.getWorld(); + if (world == null || world.getUID() == null || world.getName() == null) + return Map.of("location_status", "unavailable"); + return Map.of("world_id", world.getUID().toString(), "world_name", world.getName(), + "x", origin.getX(), "y", origin.getY(), "z", origin.getZ()); + } + private static boolean unobstructed(Location origin, LivingEntity target) { var world = origin.getWorld(); if (world == null) return false; var location = target.getLocation(); if (location.getWorld() != world) return false; diff --git a/src/main/java/games/dmg/fantasystick/persistence/FrostNovaSettings.java b/src/main/java/games/dmg/fantasystick/persistence/FrostNovaSettings.java index d191629..ef30d2e 100644 --- a/src/main/java/games/dmg/fantasystick/persistence/FrostNovaSettings.java +++ b/src/main/java/games/dmg/fantasystick/persistence/FrostNovaSettings.java @@ -71,10 +71,11 @@ public final class FrostNovaSettings implements AutoCloseable { public String value(String key) { return effectiveValues.get(key); } public FrostNova.Settings settings() { return parse(effectiveValues); } - public synchronized void publish(Update update) { + public synchronized boolean publish(Update update) { Objects.requireNonNull(update); - if (update.sequence() <= publishedSequence) return; + if (update.sequence() <= publishedSequence) return false; parse(update.values()); effectiveValues = update.values(); publishedSequence = update.sequence(); + return true; } public CompletionStage set(String key, String value) { diff --git a/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java b/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java index f02ca63..4d364c5 100644 --- a/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java +++ b/src/main/java/games/dmg/fantasystick/session/EquipmentAdminCommand.java @@ -1389,8 +1389,11 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { private void frostNovaConfiguration(CommandSender sender, String[] args) { String key = args[1]; + var actor = abilityConfigEvents == null ? null : abilityConfigEvents.capture(sender); + String before = frostNovaSettings.value(key); if (args.length == 2) { - sender.sendMessage(key + "=" + frostNovaSettings.value(key) + " (applies to future Frost Nova casts only)"); return; + if (abilityConfigEvents != null) abilityConfigEvents.read(actor, "frost_nova", key, before); + sender.sendMessage(key + "=" + before + " (applies to future Frost Nova casts only)"); return; } java.util.concurrent.CompletionStage operation; try { operation = frostNovaSettings.set(key, args[2]); } @@ -1402,12 +1405,14 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable { if (closed) return; try { nextTick.accept(() -> { if (closed) return; - if (failure == null) { - frostNova.configure(saved.settings()); abilities.replace(frostNova.definition()); frostNovaSettings.publish(saved); + boolean published = failure == null && frostNovaSettings.publish(saved); + if (published) { + frostNova.configure(saved.settings()); abilities.replace(frostNova.definition()); + if (abilityConfigEvents != null) abilityConfigEvents.changed(actor, "frost_nova", key, before, saved.value()); } if (!sender.hasPermission(PERMISSION) || sender instanceof org.bukkit.entity.Player player && !player.isOnline()) return; - sender.sendMessage(failure == null + sender.sendMessage(published ? "Saved " + key + "=" + saved.value() + " for future Frost Nova casts; active slows and deadlines are unchanged." : "Frost Nova configuration save failed; the effective setting is unchanged."); }); } catch (RuntimeException rejected) { report(null, "config-response", rejected); } diff --git a/src/nativeTest/java/games/dmg/fantasystick/FrostNovaNativeTest.java b/src/nativeTest/java/games/dmg/fantasystick/FrostNovaNativeTest.java index be8fa7c..11ba700 100644 --- a/src/nativeTest/java/games/dmg/fantasystick/FrostNovaNativeTest.java +++ b/src/nativeTest/java/games/dmg/fantasystick/FrostNovaNativeTest.java @@ -99,6 +99,45 @@ class FrostNovaNativeTest { assertEquals(60L, fixture.delayedTicks.getLast()); fixture.delayed.getLast().run(); assertFalse(enemyEffects.containsKey(PotionEffectType.SLOWNESS)); assertFalse(opponentEffects.containsKey(PotionEffectType.SLOWNESS)); } + var records = events(data); + for (var type : List.of("ability.learned", "ability.assigned", "ability.cast", "ability.resolved")) + assertEquals(1, abilityEvents(records, type).size(), type); + assertEquals(2, abilityEvents(records, "combat.damage").size(), "One accepted record per eligible target"); + for (var type : List.of("effect.applied", "effect.ended")) + assertEquals(2, abilityEvents(records, type).size(), "Only the two owned Slowness layers: " + type); + var damageEvents = abilityEvents(records, "combat.damage"); + assertEquals(2, records.stream().filter(event -> event.get("type").getAsString().endsWith("combat.damage")).count(), + "The generic native observer cannot duplicate either owned burst hit"); + assertEquals(2, damageEvents.stream().map(event -> event.getAsJsonObject("data").get("application_id").getAsString()).distinct().count()); + assertTrue(damageEvents.stream().allMatch(event -> event.getAsJsonObject("data").has("target_location") + && event.getAsJsonObject("data").get("actual_amount").getAsDouble() == 8 + && event.getAsJsonObject("data").get("damage_kind").getAsString().equals("owned_area_burst"))); + var applied = abilityEvents(records, "effect.applied"); + assertEquals(2, applied.stream().map(event -> event.getAsJsonObject("data").get("application_id").getAsString()).distinct().count()); + assertTrue(applied.stream().allMatch(event -> event.getAsJsonObject("data").get("amplifier").getAsInt() == 1)); + assertEquals(2, abilityEvents(records, "effect.ended").stream() + .filter(event -> event.getAsJsonObject("data").get("reason").getAsString().equals("expired")).count()); + var outcome = abilityEvents(records, "ability.resolved").getFirst().getAsJsonObject("data"); + assertEquals("hit", outcome.get("outcome").getAsString()); + assertEquals(2, outcome.get("accepted_count").getAsInt()); + assertEquals(3, outcome.get("attempt_count").getAsInt()); + assertEquals(5, outcome.get("candidate_count").getAsInt(), "Duplicate nearby references are deduplicated"); + assertTrue(outcome.getAsJsonObject("burst_location").has("world_id")); + } + + private static List events(Path root) throws Exception { + var values = new ArrayList(); + try (var files = java.nio.file.Files.walk(root.resolve("events"))) { + for (var file : files.filter(path -> path.toString().endsWith(".jsonl")).toList()) + for (var line : java.nio.file.Files.readAllLines(file)) + if (!line.isBlank()) values.add(com.google.gson.JsonParser.parseString(line).getAsJsonObject()); + } + return values; + } + private static List abilityEvents(List events, String suffix) { + return events.stream().filter(event -> event.get("type").getAsString().endsWith(suffix) + && event.getAsJsonObject("data").has("ability_id") + && event.getAsJsonObject("data").get("ability_id").getAsString().equals("frost_nova")).toList(); } @SuppressWarnings("unchecked") @@ -274,6 +313,18 @@ class FrostNovaNativeTest { var enemyEffects = effects(enemy); var applied = new HashMap(); damage(fixture, enemy, applied); use(fixture, caster); drain(fixture, 2); assertEquals(12, applied.get(enemy.getUniqueId()), 1.0e-9); assertEquals(3, enemyEffects.get(PotionEffectType.SLOWNESS).getAmplifier()); assertEquals(120L, fixture.delayedTicks.getLast()); + try (var channel = java.nio.channels.FileChannel.open(data.resolve(".config.lock"), + java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.WRITE); + var lock = channel.lock()) { + assertTrue(lock.isValid()); + fixture.command.execute(sender.port, "fstickadmin", + new String[]{"config", "frost-nova-radius-blocks", "11"}); + var failed = fixture.tasks.poll(5, TimeUnit.SECONDS); assertNotNull(failed); failed.run(); + } + assertEquals("10", ((games.dmg.fantasystick.persistence.FrostNovaSettings) + FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin, "frostNovaSettings")) + .value("frost-nova-radius-blocks")); + assertTrue(sender.messages.getLast().contains("save failed")); fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks", "0"}); assertTrue(sender.messages.getLast().contains("invalid")); fixture.command.execute(sender.port, "fantasystick", new String[]{"config", "frost-nova-radius-blocks", "10", "extra"}); @@ -286,6 +337,12 @@ class FrostNovaNativeTest { assertEquals(java.time.Duration.ofSeconds(3), saved.cooldown()); assertEquals(0, new BigDecimal("6").compareTo(saved.parameters().get("slowness-duration-seconds"))); } + var config = events(data).stream().filter(event -> event.get("type").getAsString().endsWith("config.read") + || event.get("type").getAsString().endsWith("config.changed")) + .filter(event -> event.getAsJsonObject("data").has("key") + && event.getAsJsonObject("data").get("key").getAsString().startsWith("frost-nova-")).toList(); + assertEquals(6, config.size(), "One authorized read and five acknowledged saves, no denied/invalid successes"); + assertEquals("8", config.getFirst().getAsJsonObject("data").get("after").getAsString()); for (String invalid : List.of("frost-nova-base-damage: -1\n", "frost-nova-cooldown-seconds: -1\n", "frost-nova-radius-blocks: 0\n", "frost-nova-slowness-amplifier: -1\n", "frost-nova-slowness-duration-seconds: 0\n")) { var directory = data.resolve(Integer.toHexString(invalid.hashCode())); java.nio.file.Files.createDirectories(directory); diff --git a/src/test/java/games/dmg/fantasystick/persistence/FrostNovaSettingsTest.java b/src/test/java/games/dmg/fantasystick/persistence/FrostNovaSettingsTest.java index 34cdbb3..6d7aa1d 100644 --- a/src/test/java/games/dmg/fantasystick/persistence/FrostNovaSettingsTest.java +++ b/src/test/java/games/dmg/fantasystick/persistence/FrostNovaSettingsTest.java @@ -21,7 +21,8 @@ class FrostNovaSettingsTest { var cooldown = settings.set(FrostNovaSettings.COOLDOWN, "24").toCompletableFuture(); var savedRange = range.get(5, TimeUnit.SECONDS); var savedCooldown = cooldown.get(5, TimeUnit.SECONDS); assertEquals(5, settings.settings().radius(), 0); - settings.publish(savedCooldown); settings.publish(savedRange); + assertTrue(settings.publish(savedCooldown)); + assertFalse(settings.publish(savedRange), "A late save callback cannot republish stale settings or claim an event"); assertEquals(7, settings.settings().radius(), 0); assertEquals(java.time.Duration.ofSeconds(24), settings.settings().cooldown()); var yaml = (Map) new org.yaml.snakeyaml.Yaml().load(Files.readString(data.resolve("config.yml")));