feat(events): audit training owners and drain preference intents
Release / release (push) Failing after 11m16s

This commit is contained in:
dmg committed 2026-10-02 15:46:56 -04:00
1 parent 65a76b7fc4
commit 6f8e83a2e8
20 files changed
+1463 -22

No files matched your search

@@ -187,6 +187,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
private games.dmg.fantasystick.events.PartyEventBridge partyAuditEvents;
private games.dmg.fantasystick.events.CombatRewardEventBridge combatRewardEvents;
private java.util.concurrent.CompletionStage<Void> combatRewardAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.TrainingEventBridge trainingAuditEvents;
private java.util.concurrent.CompletionStage<Void> trainingAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.ArmorEventBridge armorAuditEvents;
private java.util.concurrent.CompletionStage<Void> armorAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
private games.dmg.fantasystick.events.CoinEventBridge coinEvents;
@@ -900,6 +902,10 @@ public final class FantasyStickPlugin extends JavaPlugin {
partyAuditEvents = new games.dmg.fantasystick.events.PartyEventBridge(eventLog::emit, Clock.systemUTC());partyManagement.attachEvents(partyAuditEvents);admin.attachPartyEvents(partyAuditEvents);
partyCombat.attachProtectionEvents(new games.dmg.fantasystick.events.PartyProtectionEventBridge(
eventLog::emit, Clock.systemUTC()));
trainingAuditEvents = new games.dmg.fantasystick.events.TrainingEventBridge(eventLog::emit, getDataFolder().toPath(),
failure -> getLogger().log(Level.WARNING, "Training event intent failed", failure));
admin.attachTrainingEvents(trainingAuditEvents);
trainingDummyController.attachEvents(trainingAuditEvents);
armorAuditEvents = new games.dmg.fantasystick.events.ArmorEventBridge(eventLog::emit, getDataFolder().toPath(),
failure -> getLogger().log(Level.WARNING, "Armor event intent failed", failure));
if (armorMarket != null) armorMarket.attachEvents(armorAuditEvents);
@@ -1078,6 +1084,11 @@ public final class FantasyStickPlugin extends JavaPlugin {
if (failure != null) getLogger().log(Level.WARNING, "Previous passive potion event drain failed", failure);
if (replayPassivePotionEvents != null) replayPassivePotionEvents.replay();
});
var replayTrainingEvents = trainingAuditEvents;
trainingAuditDrain.whenComplete((ignored, failure) -> {
if (failure != null) getLogger().log(Level.WARNING, "Previous training event drain failed", failure);
if (replayTrainingEvents != null) replayTrainingEvents.replay();
});
var replayArmorEvents = armorAuditEvents;
armorAuditDrain.whenComplete((ignored, failure) -> {
if (failure != null) getLogger().log(Level.WARNING, "Previous armor event drain failed", failure);
@@ -1186,6 +1197,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
var closingPartyCapacityEvents = partyCapacityEvents; partyCapacityEvents = null;
var closingSheetPackEvents = sheetResourcePackEvents; sheetResourcePackEvents = null;
var closingGrantEvents = adminExperienceEvents; adminExperienceEvents = null;
var closingTrainingEvents = trainingAuditEvents; trainingAuditEvents = null;
var closingArmorEvents = armorAuditEvents; armorAuditEvents = null;
var closingCoinEvents = coinEvents;
var closingCombatRewardEvents = combatRewardEvents;
@@ -1309,7 +1321,6 @@ public final class FantasyStickPlugin extends JavaPlugin {
if (closingAdmin != null) cleanup("admin command", closingAdmin::close);
if (closingFeedbackCommand != null) cleanup("feedback command", closingFeedbackCommand::close);
if (closingParticlesCommand != null) cleanup("particles command", closingParticlesCommand::close);
if (closingFeedbackPreferences != null) cleanup("feedback preferences", closingFeedbackPreferences::close);
if (closingSettings != null) cleanup("configuration", closingSettings::close);
if (closingFireballSettings != null) cleanup("Fireball configuration", closingFireballSettings::close);
if (closingGreatSwordSettings != null) cleanup("Great Sword configuration", closingGreatSwordSettings::close);
@@ -1557,6 +1568,14 @@ public final class FantasyStickPlugin extends JavaPlugin {
closingPassivePotionEvents.close();
passivePotionAuditDrain = closingPassivePotionEvents.drained();
});
if (closingTrainingEvents != null) cleanup("training event intent drain", () -> {
var registrationsDrained = closingTrainingDummies == null
? java.util.concurrent.CompletableFuture.<Void>completedFuture(null) : closingTrainingDummies.drained();
trainingAuditDrain = registrationsDrained.handle((ignored, failure) -> {
if (failure != null) getLogger().log(Level.WARNING, "Training registration drain failed", failure);
closingTrainingEvents.close(); return null;
}).thenCompose(ignored -> closingTrainingEvents.drained());
});
if (closingArmorEvents != null) cleanup("armor event intent drain", () -> {
var marketDrained = closingArmorMarket == null
? java.util.concurrent.CompletableFuture.<Void>completedFuture(null) : closingArmorMarket.drained();
@@ -1669,6 +1688,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
}).thenCompose(ignored -> closingRareEvents.drained());
});
if (closingEventLog != null) cleanup("local events", closingEventLog::close);
// Writer shutdown can still acknowledge already accepted preference exports.
if (closingFeedbackPreferences != null) cleanup("feedback preferences", closingFeedbackPreferences::close);
if (closingVitals != null) cleanup("native health hooks", closingVitals::close);
unregister(closingModes);
unregister(closingChat);
@@ -435,7 +435,14 @@ public final class AbilityEngine implements Consumer<ControlInput>, AutoCloseabl
@Override public void damage(org.bukkit.entity.LivingEntity target, double amount,
org.bukkit.damage.DamageSource source) {
Objects.requireNonNull(target); Objects.requireNonNull(source);
var measured = trainingDamage.apply(input.player(), target, () -> target.damage(amount, source));
games.dmg.fantasystick.training.TrainingDamage.Source metadata = null;
try {
var record = sessions.currentRecord(input.session()).orElse(null);
if (record != null) metadata = new games.dmg.fantasystick.training.TrainingDamage.Source(
audit == null ? UUID.randomUUID() : audit.actionId(), input.session().player(), record.id(), record.name(),
input.session().session(), definition.name(), definition.id());
} catch (RuntimeException ignored) { /* Unavailable audit metadata cannot change the existing effect. */ }
var measured = trainingDamage.apply(input.player(), target, metadata, () -> target.damage(amount, source));
measured.ifPresent(value -> report(AbilityReport.Type.DAMAGE, target, value));
}
@Override public void report(AbilityReport.Type type, Entity target, java.math.BigDecimal amount) {
@@ -98,7 +98,11 @@ public final class BasicAttack implements Consumer<ControlInput>, Listener, Auto
pending = attempt;
boolean completed = false;
try {
var measured = trainingDamage.apply(input.player(), target, () -> target.damage(nativeDamage, input.player()));
var measurementSource = new games.dmg.fantasystick.training.TrainingDamage.Source(
action == null ? java.util.UUID.randomUUID() : action.id(), input.session().player(), record.id(),
record.name(), input.session().session(), "Basic Attack", null);
var measured = trainingDamage.apply(input.player(), target, measurementSource,
() -> target.damage(nativeDamage, input.player()));
measured.ifPresent(amount -> {
attempt.accepted = true;
if (feedback != null) feedback.report("Basic Attack", input.player(), AbilityReport.Type.DAMAGE, target, amount);
@@ -25,6 +25,7 @@ public final class PreferenceEventBridge {
private final EquipmentSessions sessions;
private final PlayerFeedbackPreferences preferences;
private final Consumer<Throwable> failures;
private final java.util.Set<UUID> inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet();
public PreferenceEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink, Clock clock,
EquipmentSessions sessions, PlayerFeedbackPreferences preferences,
@@ -184,15 +185,32 @@ public final class PreferenceEventBridge {
data.put("after", Boolean.toString(action.requested()));
data.put("preference_revision", Long.toString(preferenceSequence));
}
if (acknowledgedIntent) {
if (!inFlight.add(action.id())) return;
if (preferences.pendingEvents().stream().noneMatch(intent -> intent.actionId().equals(action.id()))) {
inFlight.remove(action.id());
return; // A stale snapshot cannot replay an already acknowledged preference.
}
}
try {
var input = new EventInput(UUID.nameUUIDFromBytes(("fantasystick:preference:"+action.id()+":"+type)
.getBytes(StandardCharsets.UTF_8)), action.id(), type.equals("preference.changed") ? action.time()
: clock.instant(), type, action.context(), Map.copyOf(data));
var result = sink.apply(input);
if (acknowledgedIntent) result.whenComplete((delivery, failure) -> {
if (failure == null && delivery != LocalEventLog.Delivery.REJECTED)
preferences.acknowledgeEvent(action.id());
if (failure != null || delivery == LocalEventLog.Delivery.REJECTED) {
inFlight.remove(action.id()); // Rejected evidence remains available for a real retry.
return;
}
preferences.acknowledgeEvent(action.id()).whenComplete((ignored, acknowledgementFailure) -> {
if (acknowledgementFailure == null) inFlight.remove(action.id());
else try { failures.accept(acknowledgementFailure); } catch (RuntimeException ignoredFailure) { }
// Accepted delivery must not be exported twice while its durable acknowledgement is uncertain.
});
});
} catch (RuntimeException ignored) { /* Logging cannot affect the command or persistent state. */ }
} catch (RuntimeException ignored) {
if (acknowledgedIntent) inFlight.remove(action.id());
/* Logging cannot affect the command or persistent state. */
}
}
}
@@ -0,0 +1,167 @@
package games.dmg.fantasystick.events;
import games.dmg.fantasystick.session.EquipmentSessions;
import games.dmg.fantasystick.training.TrainingDummy;
import games.dmg.fantasystick.training.TrainingDummyController;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Clock;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.function.Consumer;
import java.util.function.Function;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/** Immutable acknowledged dummy-owner records; replay has no gameplay authority. */
public final class TrainingEventBridge implements AutoCloseable {
public record Actor(String kind, UUID playerId, String playerName, EventInput.Context context) {}
private final FeatureEventOutbox outbox;
private final Clock clock = Clock.systemUTC();
public TrainingEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
Path data, Consumer<Throwable> failures) {
outbox = new FeatureEventOutbox(data, "training-event-intents", Set.of("training_dummy.placed", "training_dummy.removed", "training_dummy.measured"), sink, failures);
}
public Actor actor(CommandSender sender, EquipmentSessions sessions, org.bukkit.Location input) {
String kind = sender instanceof Player ? "player" : sender instanceof org.bukkit.command.BlockCommandSender ? "command_block" : "console";
if (!(sender instanceof Player player)) return new Actor(kind, null, null, null);
UUID id = null, character = null, session = null; String name = null, characterName = null;
EventInput.Location location = null;
try { id = player.getUniqueId(); } catch (RuntimeException ignored) { }
try { name = player.getName(); } catch (RuntimeException ignored) { }
try {
var active = id == null ? null : sessions.active(id).filter(sessions::current).orElse(null);
var record = active == null ? null : sessions.currentRecord(active).orElse(null);
if (record != null) { character = record.id(); characterName = record.name(); session = active.session(); }
} catch (RuntimeException ignored) { }
try {
var at = input == null ? player.getLocation() : input;
if (at.getWorld() != null) location = new EventInput.Location(at.getWorld().getUID(), at.getWorld().getName(),
at.getX(), at.getY(), at.getZ(), clock.instant(), "native");
} catch (RuntimeException ignored) { }
try { return new Actor(kind, id, name, new EventInput.Context(id, name, character, characterName, session, location)); }
catch (RuntimeException unavailable) { return new Actor(kind, id, name, null); }
}
public void registration(String type, UUID operation, TrainingDummy dummy, Actor actor,
TrainingDummyController.Observed entities, String outcome) {
try {
var values = new LinkedHashMap<String, Object>();
values.put("actor_kind", actor == null ? "unavailable" : actor.kind());
values.put("request_actor_kind", actor == null ? "unavailable" : actor.kind());
values.put("actor_capture_quality", actor == null || "player".equals(actor.kind()) && actor.context() == null ? "unavailable" : "native");
if (actor != null && actor.playerId() != null) values.put("request_player_id", actor.playerId().toString());
if (actor != null && actor.playerName() != null) values.put("request_player_name", actor.playerName());
values.put("operation_id", operation.toString()); values.put("dummy_id", dummy.id().toString());
values.put("dummy_name", dummy.name()); values.put("dummy_display_name", dummy.displayName());
values.put("revision_capture_quality", dummy.revision() == null ? "unavailable" : "persisted");
if (dummy.revision() != null) values.put("dummy_revision", dummy.revision().toString());
values.put("world_id", dummy.world().toString()); values.put("x", dummy.x()); values.put("y", dummy.y());
values.put("z", dummy.z()); values.put("yaw", (double) dummy.yaw()); values.put("pitch", (double) dummy.pitch());
values.put("chunk_status", entities.chunkStatus()); values.put("entity_capture_quality", entities.quality());
values.put("entity_ids", entities.ids().stream().map(UUID::toString).toList());
if (entities.ids().size() == 1) values.put("entity_id", entities.ids().getFirst().toString());
values.put("entity_outcome", outcome); values.put("outcome", "acknowledged");
var id = UUID.nameUUIDFromBytes(("fantasystick:training:" + operation + ":" + type).getBytes(StandardCharsets.UTF_8));
outbox.accepted(new EventInput(id, operation, clock.instant(), type, actor == null ? null : actor.context(), Map.copyOf(values)));
} catch (RuntimeException ignored) { /* Audit cannot undo registration or native reconciliation. */ }
}
public record Capture(games.dmg.fantasystick.training.TrainingDamage.Source source, String playerName,
EventInput.Location location, EventInput.Context context) {}
public Capture capture(Player player, games.dmg.fantasystick.training.TrainingDamage.Source source) {
String name = null; EventInput.Location location = null; EventInput.Context context = null;
try { name = player.getName(); } catch (RuntimeException ignored) { }
try {
var at = player.getLocation();
if (at.getWorld() != null) location = new EventInput.Location(at.getWorld().getUID(), at.getWorld().getName(),
at.getX(), at.getY(), at.getZ(), clock.instant(), "native");
} catch (RuntimeException ignored) { }
try { context = new EventInput.Context(source.playerId(), name, source.characterId(), source.characterName(), source.sessionId(), location); }
catch (RuntimeException ignored) { }
return new Capture(source, name, location, context);
}
public EventInput measurement(Capture capture, UUID causation, TrainingDummy dummy, org.bukkit.event.entity.EntityDamageEvent event,
java.math.BigDecimal amount) {
try {
var source = capture.source(); var values = new LinkedHashMap<String, Object>();
UUID measurement = UUID.nameUUIDFromBytes(("fantasystick:training:" + causation + ":measured").getBytes(StandardCharsets.UTF_8));
values.put("measurement_id", measurement.toString()); values.put("damage_causation_id", causation.toString());
values.put("attack_name", source.attackName());
if (source.abilityId() != null) values.put("ability_id", source.abilityId());
values.put("source_player_id", source.playerId().toString()); values.put("source_character_id", source.characterId().toString());
values.put("source_session_id", source.sessionId().toString()); values.put("source_character_name", source.characterName());
if (capture.playerName() != null) values.put("source_player_name", capture.playerName());
values.put("actor_capture_quality", capture.context() == null ? "unavailable" : "native");
values.put("dummy_id", dummy.id().toString()); values.put("dummy_name", dummy.name()); values.put("dummy_display_name", dummy.displayName());
values.put("revision_capture_quality", dummy.revision() == null ? "unavailable" : "persisted");
if (dummy.revision() != null) values.put("dummy_revision", dummy.revision().toString());
values.put("entity_id", event.getEntity().getUniqueId().toString()); values.put("final_amount", amount.toPlainString());
values.put("native_prior_cancelled", false); values.put("dummy_containment_cancelled", true);
var modifiers = new LinkedHashMap<String, String>();
boolean completeModifiers = true;
for (var modifier : org.bukkit.event.entity.EntityDamageEvent.DamageModifier.values()) {
try {
if (event.isApplicable(modifier)) modifiers.put(modifier.name().toLowerCase(java.util.Locale.ROOT),
java.math.BigDecimal.valueOf(event.getDamage(modifier)).stripTrailingZeros().toPlainString());
} catch (RuntimeException unavailable) { completeModifiers = false; }
}
values.put("native_modifiers", Map.copyOf(modifiers));
values.put("native_modifier_capture_quality", completeModifiers ? "native" : "unavailable");
projectile(values, event);
if (capture.location() != null) values.put("source_location", coordinates(capture.location()));
else values.put("source_location_capture_quality", "unavailable");
try {
var at = event.getEntity().getLocation(); var world = at.getWorld();
if (world != null) values.put("target_location", coordinates(new EventInput.Location(world.getUID(), world.getName(),
at.getX(), at.getY(), at.getZ(), clock.instant(), "native")));
else values.put("target_location_capture_quality", "unavailable");
} catch (RuntimeException unavailable) { values.put("target_location_capture_quality", "unavailable"); }
values.put("outcome", "measured");
return new EventInput(measurement, source.actionId(), clock.instant(), "training_dummy.measured", capture.context(), Map.copyOf(values));
} catch (RuntimeException unavailable) { return null; }
}
private void projectile(Map<String, Object> values, org.bukkit.event.entity.EntityDamageEvent event) {
org.bukkit.entity.Entity direct;
try { direct = event.getDamageSource().getDirectEntity(); }
catch (RuntimeException unavailable) { values.put("direct_entity_capture_quality", "unavailable"); return; }
if (!(direct instanceof org.bukkit.entity.Projectile projectile)) return;
try {
values.put("projectile_id", projectile.getUniqueId().toString());
values.put("projectile_capture_quality", "native");
} catch (RuntimeException unavailable) { values.put("projectile_capture_quality", "unavailable"); }
var flight = new LinkedHashMap<String, Object>();
try {
var at = projectile.getLocation(); var world = at.getWorld();
if (world == null) flight.put("location_capture_quality", "unavailable");
else flight.putAll(coordinates(new EventInput.Location(world.getUID(), world.getName(),
at.getX(), at.getY(), at.getZ(), clock.instant(), "native")));
} catch (RuntimeException unavailable) { flight.put("location_capture_quality", "unavailable"); }
try {
var velocity = projectile.getVelocity();
if (Double.isFinite(velocity.getX()) && Double.isFinite(velocity.getY()) && Double.isFinite(velocity.getZ())) {
flight.put("velocity_x", velocity.getX()); flight.put("velocity_y", velocity.getY()); flight.put("velocity_z", velocity.getZ());
} else flight.put("velocity_capture_quality", "unavailable");
} catch (RuntimeException unavailable) { flight.put("velocity_capture_quality", "unavailable"); }
flight.put("capture_boundary", "native_damage_interception");
values.put("flight_context", Map.copyOf(flight));
}
private static Map<String, Object> coordinates(EventInput.Location location) {
return Map.of("world_id", location.worldId().toString(), "world_name", location.worldName(), "x", location.x(),
"y", location.y(), "z", location.z(), "captured_at", location.capturedAt().toString(), "capture_quality", location.quality());
}
public void measured(EventInput input) {
try { if (input != null) outbox.accepted(input); } catch (RuntimeException ignored) { /* Never gameplay. */ }
}
public void replay() { outbox.replay(); }
public CompletionStage<Void> drained() { return outbox.drained(); }
@Override public void close() { outbox.close(); }
}
@@ -194,6 +194,10 @@ public final class PlayerFeedbackPreferences implements AutoCloseable {
public CompletionStage<Void> acknowledgeEvent(UUID action) {
Objects.requireNonNull(action);
synchronized (this) {
if (closed) return CompletableFuture.failedStage(new IOException("Player preferences closed"));
pending++;
}
try {
return CompletableFuture.runAsync(() -> {
try (var channel = FileChannel.open(directory.resolve(".player-preferences.lock"),
@@ -208,9 +212,12 @@ public final class PlayerFeedbackPreferences implements AutoCloseable {
synchronized (this) { pendingEvents.remove(action); }
} catch (IOException | OverlappingFileLockException failure) {
throw new java.util.concurrent.CompletionException(failure);
}
} finally { finished(); }
}, worker).minimalCompletionStage();
} catch (RejectedExecutionException closedWorker) { return CompletableFuture.failedStage(closedWorker); }
} catch (RejectedExecutionException closedWorker) {
finished();
return CompletableFuture.failedStage(closedWorker);
}
}
private CompletionStage<Update> set(UUID account, Preference preference, boolean enabled) {
@@ -39,7 +39,8 @@ public final class YamlTrainingDummyRepository {
var row = map(value);
result.add(new TrainingDummy(UUID.fromString(text(row.get("dummy-id"))), text(row.get("name")),
UUID.fromString(text(row.get("world"))), decimal(row.get("x")), decimal(row.get("y")),
decimal(row.get("z")), (float) decimal(row.get("yaw")), (float) decimal(row.get("pitch"))));
decimal(row.get("z")), (float) decimal(row.get("yaw")), (float) decimal(row.get("pitch")),
row.containsKey("registration-revision") ? UUID.fromString(text(row.get("registration-revision"))) : null));
}
validate(result); return List.copyOf(result);
} catch (RuntimeException invalid) {
@@ -53,6 +54,7 @@ public final class YamlTrainingDummyRepository {
root.put("dummies", dummies.stream().sorted(Comparator.comparing(TrainingDummy::id)).map(value -> {
Map<String, Object> row = new LinkedHashMap<>();
row.put("dummy-id", value.id().toString()); row.put("name", value.name());
if (value.revision() != null) row.put("registration-revision", value.revision().toString());
row.put("world", value.world().toString()); row.put("x", Double.toString(value.x()));
row.put("y", Double.toString(value.y())); row.put("z", Double.toString(value.z()));
row.put("yaw", Float.toString(value.yaw())); row.put("pitch", Float.toString(value.pitch())); return row;
@@ -107,6 +107,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
private games.dmg.fantasystick.events.PartyEventBridge partyEvents;
private games.dmg.fantasystick.training.TrainingDummyDirectory trainingDummies;
private games.dmg.fantasystick.training.TrainingDummyController trainingDummyController;
private games.dmg.fantasystick.events.TrainingEventBridge trainingEvents;
private games.dmg.fantasystick.shop.FantasyArmorerDirectory armorers;
private games.dmg.fantasystick.shop.FantasyArmorerController armorerController;
private games.dmg.fantasystick.shop.ArmorMarket armorMarket;
@@ -362,6 +363,10 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
public void attachPartyEconomySettings(games.dmg.fantasystick.persistence.PartyEconomySettings settings){if(closed||partyEconomySettings!=null)throw new IllegalStateException("Party economy settings already attached or command closed");partyEconomySettings=Objects.requireNonNull(settings);}
public void attachGearSettings(games.dmg.fantasystick.persistence.GearSettings settings){if(closed||gearSettings!=null)throw new IllegalStateException("Gear settings already attached or command closed");gearSettings=Objects.requireNonNull(settings);}
public void attachCoinSettings(games.dmg.fantasystick.persistence.CoinSettings settings){if(closed||coinSettings!=null)throw new IllegalStateException("Coin settings already attached or command closed");coinSettings=Objects.requireNonNull(settings);}
public void attachTrainingEvents(games.dmg.fantasystick.events.TrainingEventBridge events) {
if (closed || trainingEvents != null) throw new IllegalStateException("Training events already attached or command closed");
trainingEvents = Objects.requireNonNull(events);
}
public void attachArmorEvents(games.dmg.fantasystick.events.ArmorEventBridge events) {
if (closed || armorEvents != null) throw new IllegalStateException("Armor events already attached or closed");
armorEvents = Objects.requireNonNull(events);
@@ -956,10 +961,13 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
if (args[1].equals("place") && sender instanceof org.bukkit.entity.Player player) {
String name = args.length < 3 ? "" : String.join(" ", java.util.Arrays.copyOfRange(args, 2, args.length));
var location = player.getLocation().clone();
var owner = player.getUniqueId();
var actor = trainingEvents == null ? null : trainingEvents.actor(sender, sessions, location);
var operation = UUID.randomUUID();
try {
trainingDummies.place(name, location.getWorld().getUID(), location.getX(), location.getY(),
location.getZ(), location.getYaw(), location.getPitch())
.whenComplete((saved, failure) -> placeDummyResponse(player, location, saved, failure));
.whenComplete((saved, failure) -> placeDummyResponse(player, owner, location, operation, actor, saved, failure));
} catch (IllegalArgumentException invalid) { sender.sendMessage("Training dummy name is invalid."); }
return;
}
@@ -967,7 +975,9 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
UUID id;
try { id = UUID.fromString(args[2]); }
catch (IllegalArgumentException invalid) { sender.sendMessage("Training dummy UUID is invalid."); return; }
trainingDummies.remove(id).whenComplete((removed, failure) -> removeDummyResponse(sender, id, removed, failure));
var actor = trainingEvents == null ? null : trainingEvents.actor(sender, sessions, null);
var operation = UUID.randomUUID();
trainingDummies.remove(id).whenComplete((removed, failure) -> removeDummyResponse(sender, id, operation, actor, removed, failure));
return;
}
trainingDummyUsage(sender);
@@ -977,9 +987,10 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
sender.sendMessage("Usage: /fstickadmin training-dummy <place [name...]|remove <dummy-uuid>|list>");
}
private void placeDummyResponse(org.bukkit.entity.Player player, org.bukkit.Location location,
private void placeDummyResponse(org.bukkit.entity.Player player, UUID owner, org.bukkit.Location location, UUID operation,
games.dmg.fantasystick.events.TrainingEventBridge.Actor actor,
games.dmg.fantasystick.training.TrainingDummy saved, Throwable failure) {
if (failure != null) report(player.getUniqueId(), "training-dummy-place", failure);
if (failure != null) report(owner, "training-dummy-place", failure);
if (closed) return;
try { nextTick.accept(() -> {
if (closed) return;
@@ -989,7 +1000,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
}
if (!player.isOnline() || !player.hasPermission(PERMISSION)) {
trainingDummies.remove(saved.id()).whenComplete((ignored, rollbackFailure) -> {
if (rollbackFailure != null) report(player.getUniqueId(), "training-dummy-permission-rollback", rollbackFailure);
if (rollbackFailure != null) report(owner, "training-dummy-permission-rollback", rollbackFailure);
if (!closed) nextTick.accept(() -> {
trainingDummyController.removeLoaded(saved.id());
if (player.isOnline()) player.sendMessage("Training dummy placement was cancelled because permission changed.");
@@ -1002,21 +1013,28 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
if (location.getWorld().isChunkLoaded(chunkX, chunkZ)) {
trainingDummyController.reconcile(location.getWorld().getChunkAt(chunkX, chunkZ));
}
if (trainingEvents != null) {
var observed = trainingDummyController.observed(saved);
String outcome = !observed.quality().equals("native") ? "unavailable"
: !observed.ids().isEmpty() ? "materialized" : observed.chunkStatus().equals("unloaded") ? "unloaded" : "not_materialized";
trainingEvents.registration("training_dummy.placed", operation, saved, actor, observed, outcome);
}
player.sendMessage("Placed training dummy " + saved.id() + ".");
} catch (RuntimeException entityFailure) {
report(player.getUniqueId(), "training-dummy-entity", entityFailure);
report(owner, "training-dummy-entity", entityFailure);
trainingDummies.remove(saved.id()).whenComplete((ignored, rollbackFailure) -> {
if (rollbackFailure != null) report(player.getUniqueId(), "training-dummy-rollback", rollbackFailure);
if (rollbackFailure != null) report(owner, "training-dummy-rollback", rollbackFailure);
if (!closed) nextTick.accept(() -> {
trainingDummyController.removeLoaded(saved.id());
if (player.isOnline()) player.sendMessage("Training dummy placement failed; no record or entity changed.");
});
});
}
}); } catch (RuntimeException rejected) { report(player.getUniqueId(), "training-dummy-response", rejected); }
}); } catch (RuntimeException rejected) { report(owner, "training-dummy-response", rejected); }
}
private void removeDummyResponse(CommandSender sender, UUID id,
private void removeDummyResponse(CommandSender sender, UUID id, UUID operation,
games.dmg.fantasystick.events.TrainingEventBridge.Actor actor,
java.util.Optional<games.dmg.fantasystick.training.TrainingDummy> removed, Throwable failure) {
if (failure != null) report(null, "training-dummy-remove", failure);
if (closed) return;
@@ -1029,7 +1047,18 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
restoreDummy(sender, removed.orElseThrow(), "Training dummy removal was cancelled because permission changed.");
return;
}
try { trainingDummyController.removeLoaded(id); sender.sendMessage("Removed training dummy " + id + "."); }
try {
var saved = removed.orElseThrow();
var before = trainingEvents == null ? null : trainingDummyController.observed(saved);
trainingDummyController.removeLoaded(id);
if (trainingEvents != null) {
var after = trainingDummyController.observed(saved);
String outcome = !before.quality().equals("native") || !after.quality().equals("native") ? "unavailable"
: before.ids().isEmpty() ? "none_loaded" : before.ids().stream().anyMatch(after.ids()::contains) ? "not_removed" : "removed";
trainingEvents.registration("training_dummy.removed", operation, saved, actor, before, outcome);
}
sender.sendMessage("Removed training dummy " + id + ".");
}
catch (RuntimeException entityFailure) {
report(null, "training-dummy-entity", entityFailure);
restoreDummy(sender, removed.orElseThrow(), "Training dummy removal failed; record and entity are unchanged.");
@@ -10,6 +10,14 @@ import org.bukkit.entity.Player;
public interface TrainingDamage {
Optional<BigDecimal> apply(Player source, LivingEntity target, Runnable nativeDamage);
/** Caller-owned input identity; this metadata cannot authorize or replay an attack. */
record Source(java.util.UUID actionId, java.util.UUID playerId, java.util.UUID characterId,
String characterName, java.util.UUID sessionId, String attackName, String abilityId) {}
default Optional<BigDecimal> apply(Player source, LivingEntity target, Source metadata, Runnable nativeDamage) {
return apply(source, target, nativeDamage);
}
default boolean target(org.bukkit.entity.Entity entity) { return false; }
static TrainingDamage passthrough() {
@@ -4,7 +4,10 @@ import java.util.Objects;
import java.util.UUID;
/** Durable desired location for one administrator-managed training dummy. */
public record TrainingDummy(UUID id, String name, UUID world, double x, double y, double z, float yaw, float pitch) {
public record TrainingDummy(UUID id, String name, UUID world, double x, double y, double z, float yaw, float pitch, UUID revision) {
public TrainingDummy(UUID id, String name, UUID world, double x, double y, double z, float yaw, float pitch) {
this(id, name, world, x, y, z, yaw, pitch, null);
}
public TrainingDummy {
Objects.requireNonNull(id); Objects.requireNonNull(name); Objects.requireNonNull(world);
name = name.strip();
@@ -31,9 +31,13 @@ public final class TrainingDummyController implements Listener, TrainingDamage,
private final java.util.Set<Zombie> loaded = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
private Attempt pending;
private boolean closed;
private games.dmg.fantasystick.events.TrainingEventBridge events;
private static final class Attempt {
final LivingEntity target; BigDecimal amount;
final UUID causation = UUID.randomUUID();
games.dmg.fantasystick.events.TrainingEventBridge.Capture capture;
games.dmg.fantasystick.events.EventInput measurement;
Attempt(LivingEntity target) { this.target = target; }
}
@@ -49,6 +53,21 @@ public final class TrainingDummyController implements Listener, TrainingDamage,
}
}
public record Observed(String chunkStatus, java.util.List<UUID> ids, String quality) {}
public Observed observed(TrainingDummy value) {
try {
var world = plugin.getServer().getWorld(value.world());
if (world == null) return new Observed("unavailable", java.util.List.of(), "unavailable");
if (!world.isChunkLoaded(chunk(value.x()), chunk(value.z())))
return new Observed("unloaded", java.util.List.of(), "native");
var entities = world.getEntities();
if (entities == null) return new Observed("loaded", java.util.List.of(), "unavailable");
var ids = entities.stream().filter(this::tagged).filter(entity -> value.id().equals(id(entity)))
.map(Entity::getUniqueId).sorted().toList();
return new Observed("loaded", ids, "native");
} catch (RuntimeException unavailable) { return new Observed("unavailable", java.util.List.of(), "unavailable"); }
}
public boolean tagged(Entity entity) {
var data = entity.getPersistentDataContainer();
return data != null && TYPE.equals(data.get(typeKey, PersistentDataType.STRING));
@@ -93,13 +112,25 @@ public final class TrainingDummyController implements Listener, TrainingDamage,
}
}
public void attachEvents(games.dmg.fantasystick.events.TrainingEventBridge bridge) {
if (closed || events != null) throw new IllegalStateException("Training events already attached or controller closed");
events = Objects.requireNonNull(bridge);
}
@Override public Optional<BigDecimal> apply(Player source, LivingEntity target, Runnable nativeDamage) {
return apply(source, target, null, nativeDamage);
}
@Override public Optional<BigDecimal> apply(Player source, LivingEntity target, TrainingDamage.Source metadata, Runnable nativeDamage) {
Objects.requireNonNull(source); Objects.requireNonNull(target); Objects.requireNonNull(nativeDamage);
if (closed || !managed(target)) { nativeDamage.run(); return Optional.empty(); }
if (pending != null) throw new IllegalStateException("Nested training damage is unavailable");
var attempt = new Attempt(target); pending = attempt;
var attempt = new Attempt(target);
try { if (events != null && metadata != null) attempt.capture = events.capture(source, metadata); }
catch (RuntimeException ignored) { /* Unavailable audit context cannot change interception. */ }
pending = attempt;
try { nativeDamage.run(); }
finally { if (pending == attempt) pending = null; }
if (events != null) events.measured(attempt.measurement);
return Optional.ofNullable(attempt.amount);
}
@@ -171,6 +202,12 @@ public final class TrainingDummyController implements Listener, TrainingDamage,
if (attempt != null && attempt.target == event.getEntity() && managed(event.getEntity())
&& Double.isFinite(event.getFinalDamage()) && event.getFinalDamage() > 0) {
attempt.amount = BigDecimal.valueOf(event.getFinalDamage()).stripTrailingZeros();
try {
if (events != null && attempt.capture != null) {
var dummy = directory.find(id(event.getEntity())).orElse(null);
if (dummy != null) attempt.measurement = events.measurement(attempt.capture, attempt.causation, dummy, event, attempt.amount);
}
} catch (RuntimeException ignored) { /* Audit cannot interrupt native damage containment. */ }
}
event.setCancelled(true);
}
@@ -31,7 +31,7 @@ public final class TrainingDummyDirectory implements AutoCloseable {
}
public CompletableFuture<TrainingDummy> place(String name, UUID world, double x, double y, double z,
float yaw, float pitch) {
var value = new TrainingDummy(UUID.randomUUID(), name, world, x, y, z, yaw, pitch);
var value = new TrainingDummy(UUID.randomUUID(), name, world, x, y, z, yaw, pitch, UUID.randomUUID());
return submit(() -> {
var next = new ArrayList<>(snapshot); next.add(value); repository.save(next);
snapshot = List.copyOf(next); return value;