Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/crafting/ManualCraftingController.java
T
2026-09-25 12:07:48 -04:00

232 lines
12 KiB
Java

package games.dmg.fantasystick.crafting;
import games.dmg.fantasystick.items.CharacterSheets;
import games.dmg.fantasystick.persistence.CharacterRecord;
import org.bukkit.Keyed;
import games.dmg.fantasystick.persistence.CharacterStorage;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
/**
* Owns accepted manual craft lifetimes. Native entrypoints/close run on the server thread.
* nextTick must always enqueue onto that thread (never run inline), or throw on rejection.
* Diagnostics must be thread-safe, nonthrowing and independent of native player access.
* A cancellation observed before this HIGHEST handler is preserved; the event's single boolean cannot
* distinguish our containment cancellation from an independent later plugin veto.
*/
public final class ManualCraftingController implements Listener, AutoCloseable {
public record Failure(UUID player, List<UUID> characters, String operation, Throwable cause) {
public Failure { characters = List.copyOf(characters); }
}
private final CharacterStorage storage;
private final Supplier<CharacterRecord> allocate;
private final Consumer<Runnable> nextTick;
private final Function<Player, ManualDropDelivery.DropTarget> drops;
private final Consumer<Failure> failures;
private final java.util.concurrent.ConcurrentMap<UUID, Attempt> pending = new java.util.concurrent.ConcurrentHashMap<>();
private volatile boolean closed;
private games.dmg.fantasystick.events.CharacterIdentityEventBridge identityEvents;
private final java.util.Set<CraftItemEvent> handledCrafts =
java.util.Collections.newSetFromMap(new java.util.WeakHashMap<>());
public void attachIdentityEvents(games.dmg.fantasystick.events.CharacterIdentityEventBridge events) {
if (identityEvents != null || !pending.isEmpty()) throw new IllegalStateException("Craft identity events already attached or attempts started");
identityEvents = java.util.Objects.requireNonNull(events);
}
// Server-thread reservation outlives close/reopen invalidation and includes client-sync callbacks.
private final java.util.Set<UUID> delivering = new java.util.HashSet<>();
public ManualCraftingController(CharacterStorage storage, Supplier<CharacterRecord> allocate,
Consumer<Runnable> nextTick, Function<Player, ManualDropDelivery.DropTarget> drops, Consumer<Failure> failures) {
this.storage = java.util.Objects.requireNonNull(storage);
this.allocate = java.util.Objects.requireNonNull(allocate);
this.nextTick = java.util.Objects.requireNonNull(nextTick);
this.drops = java.util.Objects.requireNonNull(drops);
this.failures = java.util.Objects.requireNonNull(failures);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCraft(CraftItemEvent event) {
if (event.isCancelled() || !(event.getRecipe() instanceof Keyed keyed)
|| !CharacterSheets.RECIPE.equals(keyed.getKey())) return;
handledCrafts.add(event); // MONITOR can distinguish our containment from an existing veto.
java.util.Optional<ManualCraftPlan> plan;
try {
plan = ManualCraftPlan.capture(event);
} catch (RuntimeException failure) {
failures.accept(new Failure(event.getWhoClicked().getUniqueId(), List.of(), "plan", failure));
refuseCraft(event, "failed", "plan");
return;
} finally {
// capture must see the original cancellation state, but exceptions must never expose the plain preview.
event.setCancelled(true);
}
if (closed || plan.isEmpty() || !(event.getWhoClicked() instanceof Player player) || !player.isOnline()
|| !plan.orElseThrow().matches(player.getOpenInventory())) {
refuseCraft(event, "refused", "invalid_or_stale_preflight");
return;
}
var attempt = new Attempt(player.getUniqueId(), player, plan.orElseThrow());
if (delivering.contains(attempt.id) || pending.putIfAbsent(attempt.id, attempt) != null) return;
var audit = identityEvents;
if (audit != null) attempt.craft = audit.craft(player, attempt.plan.route().name().toLowerCase(java.util.Locale.ROOT), attempt.plan.quantity());
try {
var records = java.util.stream.IntStream.range(0, attempt.plan.quantity()).mapToObj(index -> allocate.get()).toList();
attempt.records = records;
attempt.characters = records.stream().map(CharacterRecord::id).toList();
attempt.preparation = storage.prepareCraft(records);
attempt.preparation.ready().whenComplete((batch, failure) -> schedule(attempt, batch, failure));
} catch (RuntimeException failure) {
pending.remove(attempt.id, attempt);
abandon(attempt);
failures.accept(new Failure(attempt.id, attempt.characters, "prepare", failure));
if (audit != null) audit.resolved(attempt.craft, "failed", "prepare", 0);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onCraftDecision(CraftItemEvent event) {
if (!(event.getRecipe() instanceof Keyed keyed) || !CharacterSheets.RECIPE.equals(keyed.getKey())) return;
if (handledCrafts.remove(event) || !event.isCancelled()) return;
refuseCraft(event, "cancelled", "prior_cancellation");
}
private void refuseCraft(CraftItemEvent event, String outcome, String reason) {
var audit = identityEvents;
if (audit == null || !(event.getWhoClicked() instanceof Player player)) return;
var action = audit.craft(player, "unknown", 0);
audit.resolved(action, outcome, reason, 0);
}
private void schedule(Attempt attempt, CharacterStorage.CraftBatch batch, Throwable failure) {
if (closed || pending.get(attempt.id) != attempt) {
abandon(attempt);
return;
}
try {
nextTick.accept(() -> complete(attempt, batch, failure));
} catch (RuntimeException rejected) {
pending.remove(attempt.id, attempt);
abandon(attempt);
// This branch may run on the persistence worker: diagnostics use captured IDs, never native player access.
failures.accept(new Failure(attempt.id, attempt.characters, "schedule", rejected));
}
}
private void complete(Attempt attempt, CharacterStorage.CraftBatch batch, Throwable failure) {
if (closed || pending.get(attempt.id) != attempt) {
abandon(attempt);
return;
}
if (!delivering.add(attempt.id)) return;
try {
var audit = identityEvents;
if (failure != null) {
failures.accept(new Failure(attempt.id, attempt.characters, "save", failure));
if (audit != null) audit.resolved(attempt.craft, "failed", "save", 0);
} else if (attempt.player.isOnline()) {
attempt.handoffStarted = true;
if (attempt.plan.route() == ManualCraftPlan.Route.DROP) {
var result = ManualDropDelivery.commit(attempt.plan, batch, attempt.player::getOpenInventory,
() -> !closed && pending.get(attempt.id) == attempt && attempt.player.isOnline(), drops.apply(attempt.player));
if (audit != null) {
for (int index = 0; index < result.completed(); index++) audit.created(attempt.craft, attempt.records.get(index), index);
var outcome = switch (result.status()) {
case COMPLETE -> "accepted";
case CANCELLED -> "cancelled";
case STALE -> "stale";
case UNCONFIRMED -> "uncertain";
case UNAVAILABLE, UNSUPPORTED_ROUTE -> "refused";
};
audit.resolved(attempt.craft, outcome,
"drop_" + result.status().name().toLowerCase(java.util.Locale.ROOT), result.completed());
}
if (result.status() != ManualDropDelivery.Status.COMPLETE) {
failures.accept(new Failure(attempt.id, attempt.characters, "drop-" + result.status().name().toLowerCase(java.util.Locale.ROOT), null));
}
} else {
var result = ManualCraftDelivery.commit(attempt.plan, batch, attempt.player.getOpenInventory());
attempt.handoffStarted = result == ManualCraftDelivery.Result.DELIVERED;
if (audit != null) {
if (attempt.handoffStarted) for (int index = 0; index < attempt.records.size(); index++)
audit.created(attempt.craft, attempt.records.get(index), index);
audit.resolved(attempt.craft, attempt.handoffStarted ? "accepted"
: result == ManualCraftDelivery.Result.STALE ? "stale" : "refused",
result.name().toLowerCase(java.util.Locale.ROOT), attempt.handoffStarted ? attempt.records.size() : 0);
}
}
}
} catch (RuntimeException unexpected) {
failures.accept(new Failure(attempt.id, attempt.characters, "delivery", unexpected));
if (identityEvents != null) identityEvents.resolved(attempt.craft, "uncertain", "delivery", 0);
} finally {
pending.remove(attempt.id, attempt);
abandon(attempt);
try {
if (attempt.player.isOnline()) attempt.player.updateInventory();
} catch (RuntimeException unexpected) {
failures.accept(new Failure(attempt.id, attempt.characters, "sync", unexpected));
} finally {
delivering.remove(attempt.id);
}
}
}
private static final class Attempt {
final UUID id;
final Player player;
final ManualCraftPlan plan;
List<UUID> characters = List.of();
List<CharacterRecord> records = List.of();
games.dmg.fantasystick.events.CharacterIdentityEventBridge.Craft craft;
CharacterStorage.CraftPreparation preparation;
volatile boolean handoffStarted;
final java.util.concurrent.atomic.AtomicBoolean cleanupObserved = new java.util.concurrent.atomic.AtomicBoolean();
Attempt(UUID id, Player player, ManualCraftPlan plan) {
this.id = id;
this.player = player;
this.plan = plan;
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onClose(org.bukkit.event.inventory.InventoryCloseEvent event) { invalidate(event.getPlayer().getUniqueId()); }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onOpen(org.bukkit.event.inventory.InventoryOpenEvent event) {
if (!event.isCancelled()) invalidate(event.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(org.bukkit.event.player.PlayerQuitEvent event) { invalidate(event.getPlayer().getUniqueId()); }
private void invalidate(UUID player) {
var attempt = pending.remove(player);
if (attempt != null) abandon(attempt);
}
private void abandon(Attempt attempt) {
if (attempt.preparation == null || !attempt.cleanupObserved.compareAndSet(false, true)) return;
attempt.preparation.abandon().thenAccept(cleanup -> {
if (!attempt.handoffStarted && !cleanup.retained().isEmpty()) {
failures.accept(new Failure(attempt.id, List.copyOf(cleanup.retained()), "cleanup-retained", null));
}
});
}
@Override public void close() {
closed = true;
for (var id : pending.keySet()) invalidate(id);
}
}