This commit is contained in:
1 parent
c776dca248
commit
1926dbb9f7
8 files changed
+1129
No files matched your search
@@ -161,6 +161,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.passive.LowLightVision lowLightVision;
|
||||
private games.dmg.fantasystick.passive.PassiveRegistry passiveRegistry;
|
||||
private games.dmg.fantasystick.passive.PassiveEngine passiveEngine;
|
||||
private games.dmg.fantasystick.events.LocalEventLog eventLog;
|
||||
private games.dmg.fantasystick.events.EventCaptureListener eventCapture;
|
||||
private java.util.concurrent.CompletionStage<Void> configurationDrain = java.util.concurrent.CompletableFuture.completedStage(null);
|
||||
|
||||
@Override public void onEnable() {
|
||||
@@ -688,6 +690,17 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
"Missing packaged fstickadmin command");
|
||||
adminCommand.setExecutor(admin);
|
||||
adminCommand.setTabCompleter(admin);
|
||||
try {
|
||||
eventLog = games.dmg.fantasystick.events.LocalEventLog.open(getDataFolder().toPath(), Clock.systemUTC(),
|
||||
new games.dmg.fantasystick.events.LocalEventLog.RuntimeInfo("FantasyStick",
|
||||
getServer().getVersion(), getServer().getMinecraftVersion(), getDescription().getVersion()), 1024, 134_217_728L,
|
||||
message -> getLogger().warning(message));
|
||||
eventCapture = new games.dmg.fantasystick.events.EventCaptureListener(eventLog, sessions, Clock.systemUTC());
|
||||
getServer().getPluginManager().registerEvents(eventCapture, this);
|
||||
} catch (java.io.IOException failure) {
|
||||
eventLog = null; eventCapture = null;
|
||||
getLogger().log(Level.WARNING,"Fantasy Stick local events are unavailable; gameplay remains enabled",failure);
|
||||
}
|
||||
getServer().getPluginManager().registerEvents(crafting, this);
|
||||
getServer().getPluginManager().registerEvents(guard, this);
|
||||
getServer().getPluginManager().registerEvents(anvilNames, this);
|
||||
@@ -765,6 +778,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
recipeDiscovery.discoverAll(onlinePlayers);
|
||||
for (var player : onlinePlayers) { sessions.arrive(player); revive.reconcile(player); }
|
||||
sheetResourcePack.deliverAll(onlinePlayers);
|
||||
if(eventLog!=null)eventLog.ready();
|
||||
} catch (RuntimeException | LinkageError failure) {
|
||||
try { onDisable(); }
|
||||
catch (RuntimeException | LinkageError cleanupFailure) { failure.addSuppressed(cleanupFailure); }
|
||||
@@ -786,6 +800,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
particleDelivery = null;
|
||||
combatFeedback = null;
|
||||
var closingEvents = sessionEvents; sessionEvents = null;
|
||||
var closingEventLog = eventLog; eventLog = null;
|
||||
var closingEventCapture = eventCapture; eventCapture = null;
|
||||
var closingBooks = books; books = null;
|
||||
var closingPartyEvents = partyEvents; partyEvents = null;
|
||||
var closingPartyCombat = partyCombat; partyCombat = null;
|
||||
@@ -1088,9 +1104,11 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if (closingEvents != null) cleanup("session events", closingEvents::close);
|
||||
if (closingCrafting != null) cleanup("craft attempts", closingCrafting::close);
|
||||
if (closingSessions != null) cleanup("equipment sessions", closingSessions::close);
|
||||
if (closingEventLog != null) cleanup("local events", closingEventLog::close);
|
||||
if (closingVitals != null) cleanup("native health hooks", closingVitals::close);
|
||||
unregister(closingModes);
|
||||
unregister(closingChat);
|
||||
unregister(closingEventCapture);
|
||||
unregister(closingPartyEvents);
|
||||
unregister(closingPartyCombat);
|
||||
unregister(closingPartyRegistrarController);
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package games.dmg.fantasystick.events;
|
||||
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.time.Clock;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.WeakHashMap;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.entity.EntityPickupItemEvent;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.player.PlayerDropItemEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEntityEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerItemHeldEvent;
|
||||
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.vehicle.VehicleEnterEvent;
|
||||
import org.bukkit.event.vehicle.VehicleExitEvent;
|
||||
import org.bukkit.inventory.EquipmentSlot;
|
||||
|
||||
/** Captures immutable generic native action context without changing event cancellation or gameplay. */
|
||||
public final class EventCaptureListener implements Listener {
|
||||
private record Captured(UUID action, EventInput.Context context, String kind, Map<String, Object> details) { }
|
||||
private final LocalEventLog events;
|
||||
private final EquipmentSessions sessions;
|
||||
private final Clock clock;
|
||||
private final Map<Object, Captured> captured = java.util.Collections.synchronizedMap(new WeakHashMap<>());
|
||||
|
||||
public EventCaptureListener(LocalEventLog events, EquipmentSessions sessions, Clock clock) {
|
||||
this.events = Objects.requireNonNull(events);
|
||||
this.sessions = Objects.requireNonNull(sessions);
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = false)
|
||||
public void observe(PlayerInteractEvent event) {
|
||||
if (event.getHand() != EquipmentSlot.HAND) return;
|
||||
var snapshot = context(event.getPlayer()).orElse(null);
|
||||
if (snapshot == null) return;
|
||||
String kind = switch (event.getAction()) {
|
||||
case RIGHT_CLICK_BLOCK, LEFT_CLICK_BLOCK, PHYSICAL -> "interact_block";
|
||||
case RIGHT_CLICK_AIR, LEFT_CLICK_AIR -> "interact_item";
|
||||
};
|
||||
var details = new LinkedHashMap<String, Object>();
|
||||
details.put("entry_point", "PlayerInteractEvent");
|
||||
details.put("native_action", event.getAction().name());
|
||||
details.put("initially_cancelled", event.isCancelled());
|
||||
if (event.getClickedBlock() != null) {details.put("target_type", event.getClickedBlock().getType().name());var target=event.getClickedBlock().getLocation();if(target!=null&&target.getWorld()!=null)details.put("target_location",locationMap(target));}
|
||||
var value = new Captured(UUID.randomUUID(), snapshot, kind, Map.copyOf(details));
|
||||
captured.put(event, value);
|
||||
emit("action.observed", value, "observed", event.isCancelled());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false)
|
||||
public void resolve(PlayerInteractEvent event) { resolveCaptured(event, event); }
|
||||
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(PlayerInteractEntityEvent event){if(event.getHand()!=EquipmentSlot.HAND)return;capture(event,event.getPlayer(),"interact_entity",entity(event.getRightClicked(),"PlayerInteractEntityEvent"),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(PlayerInteractEntityEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(InventoryClickEvent event){if(event.getWhoClicked() instanceof Player player)capture(event,player,"inventory_click",Map.of("entry_point","InventoryClickEvent","slot",event.getRawSlot(),"click",event.getClick().name(),"inventory_action",event.getAction().name()),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(InventoryClickEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(PlayerDropItemEvent event){capture(event,event.getPlayer(),"drop_item",Map.of("entry_point","PlayerDropItemEvent","item_type",event.getItemDrop().getItemStack().getType().name()),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(PlayerDropItemEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(EntityPickupItemEvent event){if(event.getEntity() instanceof Player player)capture(event,player,"pickup_item",Map.of("entry_point","EntityPickupItemEvent","item_type",event.getItem().getItemStack().getType().name(),"remaining",event.getRemaining()),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(EntityPickupItemEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(PlayerItemHeldEvent event){capture(event,event.getPlayer(),"held_slot",Map.of("entry_point","PlayerItemHeldEvent","previous_slot",event.getPreviousSlot(),"new_slot",event.getNewSlot()),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(PlayerItemHeldEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(PlayerSwapHandItemsEvent event){capture(event,event.getPlayer(),"swap_hands",Map.of("entry_point","PlayerSwapHandItemsEvent"),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(PlayerSwapHandItemsEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(PlayerTeleportEvent event){var details=new LinkedHashMap<String,Object>();details.put("entry_point","PlayerTeleportEvent");details.put("cause",event.getCause().name());details.put("from_location",locationMap(event.getFrom()));if(event.getTo()!=null)details.put("to_location",locationMap(event.getTo()));capture(event,event.getPlayer(),"teleport",details,event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(PlayerTeleportEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(VehicleEnterEvent event){if(event.getEntered() instanceof Player player)capture(event,player,"vehicle_enter",entity(event.getVehicle(),"VehicleEnterEvent"),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(VehicleEnterEvent event){resolveCaptured(event,event);}
|
||||
@EventHandler(priority=EventPriority.LOWEST,ignoreCancelled=false) public void observe(VehicleExitEvent event){if(event.getExited() instanceof Player player)capture(event,player,"vehicle_exit",entity(event.getVehicle(),"VehicleExitEvent"),event);}
|
||||
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=false) public void resolve(VehicleExitEvent event){resolveCaptured(event,event);}
|
||||
|
||||
private Map<String,Object> entity(Entity entity,String entry){var details=new LinkedHashMap<String,Object>();details.put("entry_point",entry);details.put("target_id",entity.getUniqueId().toString());details.put("target_type",entity.getType().name());var target=entity.getLocation();if(target!=null&&target.getWorld()!=null)details.put("target_location",locationMap(target));return details;}
|
||||
private void capture(Object event,Player player,String kind,Map<String,Object> details,Cancellable cancellation){var snapshot=context(player).orElse(null);if(snapshot==null)return;var copied=new LinkedHashMap<>(details);copied.put("initially_cancelled",cancellation.isCancelled());var value=new Captured(UUID.randomUUID(),snapshot,kind,Map.copyOf(copied));captured.put(event,value);emit("action.observed",value,"observed",cancellation.isCancelled());}
|
||||
private void resolveCaptured(Object event,Cancellable cancellation){var value=captured.remove(event);if(value!=null)emit("action.resolved",value,cancellation.isCancelled()?"cancelled":"accepted",cancellation.isCancelled());}
|
||||
|
||||
private void emit(String type, Captured capturedAction, String outcome, boolean cancelled) {
|
||||
var data = new LinkedHashMap<>(capturedAction.details());
|
||||
data.put("action_kind", capturedAction.kind());
|
||||
data.put("outcome", outcome);
|
||||
data.put("cancelled", cancelled);
|
||||
events.emit(new EventInput(UUID.randomUUID(), capturedAction.action(), clock.instant(), type,
|
||||
capturedAction.context(), data));
|
||||
}
|
||||
|
||||
private Optional<EventInput.Context> context(Player player) {
|
||||
var active = sessions.active(player.getUniqueId()).orElse(null);
|
||||
if (active == null) return Optional.empty();
|
||||
var record = sessions.currentRecord(active).orElse(null);
|
||||
if (record == null) return Optional.empty();
|
||||
return Optional.of(new EventInput.Context(player.getUniqueId(), player.getName(), active.character(), record.name(),
|
||||
active.session(), location(player.getLocation())));
|
||||
}
|
||||
|
||||
private EventInput.Location location(Location location) {
|
||||
return new EventInput.Location(location.getWorld().getUID(), location.getWorld().getName(), location.getX(),
|
||||
location.getY(), location.getZ(), clock.instant(), "exact");
|
||||
}
|
||||
private Map<String,Object> locationMap(Location location){var value=new LinkedHashMap<String,Object>();value.put("world_id",location.getWorld().getUID().toString());value.put("world_name",location.getWorld().getName());value.put("x",location.getX());value.put("y",location.getY());value.put("z",location.getZ());return value;}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package games.dmg.fantasystick.events;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Immutable event input captured before leaving the native/gameplay thread. */
|
||||
public record EventInput(UUID id, UUID actionId, Instant time, String type, Context context,
|
||||
Map<String, Object> data) {
|
||||
public EventInput {
|
||||
Objects.requireNonNull(id);
|
||||
Objects.requireNonNull(actionId);
|
||||
Objects.requireNonNull(time);
|
||||
if (type == null || !type.matches("[a-z][a-z0-9_.-]*")) throw new IllegalArgumentException("Invalid event type");
|
||||
data = snapshotMap(Objects.requireNonNull(data));
|
||||
}
|
||||
|
||||
private static Map<String, Object> snapshotMap(Map<String, ?> source) {
|
||||
var copy = new LinkedHashMap<String, Object>();
|
||||
source.forEach((key, value) -> copy.put(Objects.requireNonNull(key), snapshot(value)));
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
private static Object snapshot(Object value) {
|
||||
if (value == null || value instanceof String || value instanceof Boolean || value instanceof UUID
|
||||
|| value instanceof java.time.temporal.TemporalAccessor) return value;
|
||||
if (value instanceof Number number) {
|
||||
if (number instanceof Double doubleValue && !Double.isFinite(doubleValue)
|
||||
|| number instanceof Float floatValue && !Float.isFinite(floatValue)) {
|
||||
throw new IllegalArgumentException("Non-finite event number");
|
||||
}
|
||||
return number;
|
||||
}
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
var copy = new LinkedHashMap<String, Object>();
|
||||
map.forEach((key, nested) -> {
|
||||
if (!(key instanceof String text)) throw new IllegalArgumentException("Non-string event key");
|
||||
copy.put(text, snapshot(nested));
|
||||
});
|
||||
return Collections.unmodifiableMap(copy);
|
||||
}
|
||||
if (value instanceof Collection<?> collection) {
|
||||
return List.copyOf(collection.stream().map(EventInput::snapshot).toList());
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported event value " + value.getClass().getName());
|
||||
}
|
||||
|
||||
public record Context(UUID playerId, String playerName, UUID characterId, String characterName,
|
||||
UUID sessionId, Location location) {
|
||||
public Context {
|
||||
if (playerId == null || playerName == null) throw new IllegalArgumentException("Incomplete player identity");
|
||||
if ((characterId == null) != (characterName == null) || characterId != null && sessionId == null
|
||||
|| characterId == null && sessionId != null) {
|
||||
throw new IllegalArgumentException("Incomplete character identity");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record Location(UUID worldId, String worldName, double x, double y, double z,
|
||||
Instant capturedAt, String quality) {
|
||||
public Location {
|
||||
Objects.requireNonNull(worldId);
|
||||
Objects.requireNonNull(worldName);
|
||||
Objects.requireNonNull(capturedAt);
|
||||
Objects.requireNonNull(quality);
|
||||
if (!Double.isFinite(x) || !Double.isFinite(y) || !Double.isFinite(z)) {
|
||||
throw new IllegalArgumentException("Non-finite event location");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package games.dmg.fantasystick.events;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Independent local CloudEvents JSONL stream with recoverable per-event pending files. */
|
||||
public final class LocalEventLog implements AutoCloseable {
|
||||
public static final String TYPE_PREFIX = "games.dmg.minecraft.fantasystick.";
|
||||
public enum Delivery { EXPORTED, DURABLE_PENDING, REJECTED }
|
||||
public record RuntimeInfo(String serverName, String platformVersion, String gameVersion, String pluginVersion) {
|
||||
public RuntimeInfo(String serverName,String gameVersion,String pluginVersion){this(serverName,gameVersion,gameVersion,pluginVersion);}
|
||||
public RuntimeInfo {
|
||||
Objects.requireNonNull(serverName);
|
||||
Objects.requireNonNull(platformVersion);
|
||||
Objects.requireNonNull(gameVersion);
|
||||
Objects.requireNonNull(pluginVersion);
|
||||
}
|
||||
}
|
||||
|
||||
private final Path root;
|
||||
private final Path pending;
|
||||
private final Path activeBoot;
|
||||
private final Clock clock;
|
||||
private final RuntimeInfo runtime;
|
||||
private final long maximumSegmentBytes;
|
||||
private final Consumer<String> diagnostic;
|
||||
private final UUID serverId;
|
||||
private final UUID bootId = UUID.randomUUID();
|
||||
private final ThreadPoolExecutor worker;
|
||||
private final CompletableFuture<Delivery> ready = new CompletableFuture<>();
|
||||
private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
private final UUID priorBoot;
|
||||
private final FileChannel lockChannel;
|
||||
private final java.nio.channels.FileLock writerLock;
|
||||
private long sequence;
|
||||
private Path segment;
|
||||
private LocalDate segmentDate;
|
||||
private long segmentBytes;
|
||||
private int segmentNumber;
|
||||
private volatile boolean closing;
|
||||
private final java.util.concurrent.atomic.AtomicLong unacceptedHandoff = new java.util.concurrent.atomic.AtomicLong();
|
||||
private final java.util.concurrent.atomic.AtomicLong lastDiagnostic = new java.util.concurrent.atomic.AtomicLong();
|
||||
|
||||
public static LocalEventLog open(Path dataFolder, Clock clock, RuntimeInfo runtime, int capacity,
|
||||
long maximumSegmentBytes, Consumer<String> diagnostic) throws IOException {
|
||||
return new LocalEventLog(dataFolder, clock, runtime, capacity, maximumSegmentBytes, diagnostic);
|
||||
}
|
||||
|
||||
private LocalEventLog(Path dataFolder, Clock clock, RuntimeInfo runtime, int capacity,
|
||||
long maximumSegmentBytes, Consumer<String> diagnostic) throws IOException {
|
||||
if (capacity < 1 || maximumSegmentBytes < 2) throw new IllegalArgumentException("Invalid event-log bound");
|
||||
this.clock = Objects.requireNonNull(clock);
|
||||
this.runtime = Objects.requireNonNull(runtime);
|
||||
this.maximumSegmentBytes = maximumSegmentBytes;
|
||||
this.diagnostic = Objects.requireNonNull(diagnostic);
|
||||
root = Objects.requireNonNull(dataFolder).resolve("events");
|
||||
if (Files.exists(root, LinkOption.NOFOLLOW_LINKS) && Files.isSymbolicLink(root)) {
|
||||
throw new IOException("Fantasy Stick events path is a symbolic link");
|
||||
}
|
||||
Files.createDirectories(root);
|
||||
pending = root.resolve("pending");
|
||||
if (Files.exists(pending, LinkOption.NOFOLLOW_LINKS) && Files.isSymbolicLink(pending)) {
|
||||
throw new IOException("Fantasy Stick pending-events path is a symbolic link");
|
||||
}
|
||||
Files.createDirectories(pending);
|
||||
activeBoot = root.resolve("active-boot");
|
||||
serverId = loadServerId();
|
||||
var lockPath=root.resolve("writer.lock");if(Files.exists(lockPath,LinkOption.NOFOLLOW_LINKS)&&Files.isSymbolicLink(lockPath))throw new IOException("Fantasy Stick writer lock is a symbolic link");
|
||||
lockChannel = FileChannel.open(lockPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
|
||||
java.nio.channels.FileLock acquired;
|
||||
try { acquired = lockChannel.tryLock(); }
|
||||
catch (java.nio.channels.OverlappingFileLockException conflict) { acquired = null; }
|
||||
if (acquired == null) { lockChannel.close(); throw new IOException("Fantasy Stick event writer is already active"); }
|
||||
writerLock = acquired;
|
||||
UUID previous;
|
||||
try {
|
||||
previous = loadPriorBoot();
|
||||
Files.writeString(activeBoot, bootId + "\n", StandardCharsets.UTF_8,
|
||||
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
|
||||
} catch (IOException | RuntimeException failure) {
|
||||
writerLock.release(); lockChannel.close(); throw failure;
|
||||
}
|
||||
priorBoot = previous;
|
||||
worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(capacity), task -> {
|
||||
var thread = new Thread(task, "fantasy-stick-events");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}, new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
|
||||
public CompletionStage<Delivery> ready() {
|
||||
if(started.compareAndSet(false,true))submitStartup(priorBoot).whenComplete((delivery,failure)->{if(failure!=null)ready.completeExceptionally(failure);else ready.complete(delivery);});
|
||||
return ready.minimalCompletionStage();
|
||||
}
|
||||
public UUID serverId() { return serverId; }
|
||||
public UUID bootId() { return bootId; }
|
||||
|
||||
public CompletionStage<Delivery> emit(EventInput input) {
|
||||
Objects.requireNonNull(input);
|
||||
if (closing) { rejectedHandoff(); return CompletableFuture.completedStage(Delivery.REJECTED); }
|
||||
return submitInternal(input, true);
|
||||
}
|
||||
|
||||
private CompletableFuture<Delivery> submitStartup(UUID priorBoot) {
|
||||
var result = new CompletableFuture<Delivery>();
|
||||
try {
|
||||
worker.execute(() -> {
|
||||
try {
|
||||
boolean interruptedTail = recoverInterruptedTails();
|
||||
int recoveredPending = recoverPending();
|
||||
if (priorBoot != null || interruptedTail || recoveredPending > 0) {
|
||||
var recovery = new LinkedHashMap<String, Object>();
|
||||
recovery.put("outcome", "incomplete_prior_lifetime");
|
||||
recovery.put("recovered_pending_count", Integer.toString(recoveredPending));
|
||||
recovery.put("interrupted_tail", interruptedTail);
|
||||
if (priorBoot != null) recovery.put("prior_boot_id", priorBoot.toString());
|
||||
store(new EventInput(UUID.randomUUID(), UUID.randomUUID(), clock.instant(),
|
||||
"game.recovery_detected", null, recovery));
|
||||
}
|
||||
result.complete(store(lifecycle("game.started", "ready")));
|
||||
} catch (Exception failure) {
|
||||
diagnostic.accept("Fantasy Stick event startup failed: " + failure.getClass().getSimpleName());
|
||||
result.complete(Delivery.REJECTED);
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
result.complete(Delivery.REJECTED);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private CompletableFuture<Delivery> submitInternal(EventInput input, boolean countRejection) {
|
||||
var result = new CompletableFuture<Delivery>();
|
||||
try {
|
||||
worker.execute(operation(input,result));
|
||||
} catch (RejectedExecutionException rejected) {
|
||||
if (countRejection) rejectedHandoff();
|
||||
result.complete(Delivery.REJECTED);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private CompletableFuture<Delivery> submitClosing(EventInput input){var result=new CompletableFuture<Delivery>();try{if(!worker.getQueue().offer(operation(input,result),5,TimeUnit.SECONDS))result.complete(Delivery.REJECTED);}catch(InterruptedException interrupted){Thread.currentThread().interrupt();result.complete(Delivery.REJECTED);}return result;}
|
||||
private Runnable operation(EventInput input,CompletableFuture<Delivery> result){return ()->{try{result.complete(store(input));}catch(Exception failure){diagnostic.accept("Fantasy Stick event write failed: "+failure.getClass().getSimpleName());result.complete(Delivery.REJECTED);}};}
|
||||
|
||||
private Delivery store(EventInput input) throws IOException {
|
||||
recoverPending();
|
||||
var rejected = unacceptedHandoff.getAndSet(0);
|
||||
if (rejected > 0 && !"logging.gap".equals(input.type())) {
|
||||
degradedDiagnostic("Fantasy Stick event queue rejected observations before durable acceptance");
|
||||
storeOne(new EventInput(UUID.randomUUID(), UUID.randomUUID(), clock.instant(), "logging.gap", null,
|
||||
Map.of("unaccepted_count", Long.toString(rejected), "reason", "bounded_handoff_rejected",
|
||||
"outcome", "uncertain")));
|
||||
}
|
||||
return storeOne(input);
|
||||
}
|
||||
|
||||
private Delivery storeOne(EventInput input) throws IOException {
|
||||
var line = encode(input, ++sequence);var bytes=(line+"\n").getBytes(StandardCharsets.UTF_8);var target=pending.resolve(input.id()+".pending");writeCreateAtomic(target,bytes);try{append(bytes);Files.deleteIfExists(target);return Delivery.EXPORTED;}catch(IOException failure){degradedDiagnostic("Fantasy Stick event export failed; durable pending work was retained");return Delivery.DURABLE_PENDING;}
|
||||
}
|
||||
|
||||
private void rejectedHandoff(){unacceptedHandoff.incrementAndGet();}
|
||||
private void degradedDiagnostic(String message){long now=System.nanoTime(),previous=lastDiagnostic.get();if((previous==0||now-previous>=Duration.ofSeconds(30).toNanos())&&lastDiagnostic.compareAndSet(previous,now))diagnostic.accept(message);}
|
||||
|
||||
private UUID loadPriorBoot() throws IOException {
|
||||
if (!Files.exists(activeBoot, LinkOption.NOFOLLOW_LINKS)) return null;
|
||||
if (Files.isSymbolicLink(activeBoot)) throw new IOException("Fantasy Stick active writer marker is a symbolic link");
|
||||
try { return UUID.fromString(Files.readString(activeBoot, StandardCharsets.UTF_8).trim()); }
|
||||
catch (IllegalArgumentException invalid) { throw new IOException("Invalid Fantasy Stick active writer marker", invalid); }
|
||||
}
|
||||
|
||||
private boolean recoverInterruptedTails() throws IOException {
|
||||
List<Path> files;
|
||||
try (var stream = Files.walk(root)) {
|
||||
files = stream.filter(path -> path.getFileName().toString().endsWith(".jsonl"))
|
||||
.sorted().toList();
|
||||
}
|
||||
boolean recovered = false;
|
||||
for (var path : files) {
|
||||
if (Files.isSymbolicLink(path)) throw new IOException("Symbolic link in Fantasy Stick event segments");
|
||||
var bytes = Files.readAllBytes(path);
|
||||
int prefix=0,cursor=0;while(cursor<bytes.length){int end=cursor;while(end<bytes.length&&bytes[end]!='\n')end++;if(end==bytes.length)break;var line=java.util.Arrays.copyOfRange(bytes,cursor,end+1);if(!validJsonObjectLine(line))break;prefix=end+1;cursor=end+1;}if(prefix==bytes.length)continue;
|
||||
recovered = true;
|
||||
var quarantine = path.resolveSibling(path.getFileName() + ".corrupt-" + UUID.randomUUID());
|
||||
try (var channel = FileChannel.open(quarantine, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
|
||||
var tail = ByteBuffer.wrap(bytes, prefix, bytes.length - prefix);
|
||||
while (tail.hasRemaining()) channel.write(tail);
|
||||
channel.force(true);
|
||||
}
|
||||
try (var channel = FileChannel.open(path, StandardOpenOption.WRITE)) {
|
||||
channel.truncate(prefix);
|
||||
channel.force(true);
|
||||
}
|
||||
}
|
||||
return recovered;
|
||||
}
|
||||
|
||||
private int recoverPending() throws IOException {
|
||||
List<Path> files;
|
||||
try (var stream = Files.list(pending)) {
|
||||
files = stream.filter(path -> path.getFileName().toString().endsWith(".pending"))
|
||||
.sorted(Comparator.comparing(path -> path.getFileName().toString())).toList();
|
||||
}
|
||||
int recovered = 0;
|
||||
for (var path : files) {
|
||||
if (Files.isSymbolicLink(path)) throw new IOException("Symbolic link in Fantasy Stick pending events");
|
||||
var bytes = Files.readAllBytes(path);
|
||||
if (!validJsonObjectLine(bytes)) {
|
||||
Files.move(path,path.resolveSibling(path.getFileName()+".corrupt-"+UUID.randomUUID()));
|
||||
continue;
|
||||
}
|
||||
append(bytes);
|
||||
Files.delete(path);
|
||||
recovered++;
|
||||
}
|
||||
return recovered;
|
||||
}
|
||||
|
||||
private static boolean validJsonObjectLine(byte[] bytes){
|
||||
if(bytes.length<3||bytes[bytes.length-1]!='\n')return false;String text;try{var decoder=StandardCharsets.UTF_8.newDecoder();decoder.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT);decoder.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT);text=decoder.decode(ByteBuffer.wrap(bytes,0,bytes.length-1)).toString();}catch(java.nio.charset.CharacterCodingException invalid){return false;}if(!text.startsWith("{")||!text.endsWith("}")||!text.contains("\"specversion\":\"1.0\"")||!text.contains("\"id\":\"")||!text.contains("\"data\":"))return false;var stack=new java.util.ArrayDeque<Character>();boolean string=false,escape=false;for(int index=0;index<text.length();index++){char value=text.charAt(index);if(string){if(escape){if(value=='u'){if(index+4>=text.length())return false;for(int digit=1;digit<=4;digit++)if(Character.digit(text.charAt(index+digit),16)<0)return false;index+=4;}else if("\"\\/bfnrt".indexOf(value)<0)return false;escape=false;}else if(value=='\\')escape=true;else if(value=='\"')string=false;else if(value<0x20)return false;continue;}if(value=='\"'){string=true;continue;}if(value=='{'||value=='[')stack.push(value);else if(value=='}'||value==']'){if(stack.isEmpty())return false;char opened=stack.pop();if(value=='}'&&opened!='{'||value==']'&&opened!='[')return false;}else if(value<0x20&&!Character.isWhitespace(value))return false;}return !string&&!escape&&stack.isEmpty();
|
||||
}
|
||||
|
||||
private void append(byte[] line) throws IOException {
|
||||
var date = LocalDate.ofInstant(clock.instant(), ZoneOffset.UTC);
|
||||
if (segment == null || !date.equals(segmentDate)
|
||||
|| segmentBytes > 0 && segmentBytes + line.length > maximumSegmentBytes) {
|
||||
openSegment(date);
|
||||
}
|
||||
try (var channel = FileChannel.open(segment, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
|
||||
var buffer = ByteBuffer.wrap(line);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
segmentBytes += line.length;
|
||||
}
|
||||
|
||||
private void openSegment(LocalDate date) throws IOException {
|
||||
var directory = root.resolve(date.toString());
|
||||
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (Files.isSymbolicLink(directory) || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Unsafe Fantasy Stick event segment directory");
|
||||
}
|
||||
} else Files.createDirectory(directory);
|
||||
if (!directory.toRealPath().getParent().equals(root.toRealPath())) {
|
||||
throw new IOException("Fantasy Stick event segment escaped its root");
|
||||
}
|
||||
while (true) {
|
||||
var candidate = directory.resolve("events-" + bootId + "-" + segmentNumber++ + ".jsonl");
|
||||
try {
|
||||
Files.createFile(candidate);
|
||||
segment = candidate;
|
||||
segmentDate = date;
|
||||
segmentBytes = 0;
|
||||
return;
|
||||
} catch (java.nio.file.FileAlreadyExistsException collision) {
|
||||
// A boot identifier collision cannot overwrite an existing segment.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private UUID loadServerId() throws IOException {
|
||||
var path = root.resolve("server-id");
|
||||
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
if (Files.isSymbolicLink(path)) throw new IOException("Fantasy Stick server identity is a symbolic link");
|
||||
try { return UUID.fromString(Files.readString(path, StandardCharsets.UTF_8).trim()); }
|
||||
catch (IllegalArgumentException invalid) { throw new IOException("Invalid Fantasy Stick server identity", invalid); }
|
||||
}
|
||||
var created = UUID.randomUUID();
|
||||
Files.writeString(path, created + "\n", StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
|
||||
return created;
|
||||
}
|
||||
|
||||
private void writeCreateAtomic(Path target, byte[] bytes) throws IOException {
|
||||
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) return;
|
||||
var temporary = pending.resolve(target.getFileName() + "." + UUID.randomUUID() + ".tmp");
|
||||
try (var channel = FileChannel.open(temporary, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
|
||||
var buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
try { Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); }
|
||||
catch (java.nio.file.AtomicMoveNotSupportedException unsupported) { Files.move(temporary, target); }
|
||||
finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
|
||||
private EventInput lifecycle(String type, String phase) {
|
||||
return new EventInput(UUID.randomUUID(), UUID.randomUUID(), clock.instant(), type, null,
|
||||
Map.of("phase", phase, "reason", "plugin_lifecycle"));
|
||||
}
|
||||
|
||||
private String encode(EventInput input, long acceptedSequence) {
|
||||
var data = new LinkedHashMap<String, Object>();
|
||||
data.putAll(input.data());
|
||||
data.put("schema_version", 1);
|
||||
data.put("server_id", serverId.toString());
|
||||
data.put("server_name", runtime.serverName());
|
||||
data.put("game_version", runtime.gameVersion());
|
||||
data.put("platform_version", runtime.platformVersion());
|
||||
data.put("plugin_version", runtime.pluginVersion());
|
||||
data.put("boot_id", bootId.toString());
|
||||
data.put("sequence", Long.toString(acceptedSequence));
|
||||
data.put("action_id", input.actionId().toString());
|
||||
var context = input.context();
|
||||
if (context != null) {
|
||||
data.put("actor_kind", "player");
|
||||
data.put("player_id", context.playerId().toString());
|
||||
data.put("player_name", context.playerName());
|
||||
if (context.characterId() != null) {
|
||||
data.put("character_id", context.characterId().toString());
|
||||
data.put("character_name", context.characterName());
|
||||
data.put("session_id", context.sessionId().toString());
|
||||
}
|
||||
if (context.location() != null) data.put("location", location(context.location()));
|
||||
} else data.put("actor_kind", "system");
|
||||
var envelope = new LinkedHashMap<String, Object>();
|
||||
envelope.put("specversion", "1.0");
|
||||
envelope.put("id", input.id().toString());
|
||||
envelope.put("source", "urn:minecraft-server:" + serverId);
|
||||
envelope.put("type", TYPE_PREFIX + input.type());
|
||||
envelope.put("time", input.time().toString());
|
||||
envelope.put("datacontenttype", "application/json");
|
||||
envelope.put("serverid", serverId.toString());
|
||||
envelope.put("servername", runtime.serverName());
|
||||
envelope.put("gameversion", runtime.gameVersion());
|
||||
if (context != null && context.playerId() != null) envelope.put("playerid", context.playerId().toString());
|
||||
if (context != null && context.characterId() != null) envelope.put("characterid", context.characterId().toString());
|
||||
envelope.put("data", data);
|
||||
return Json.encode(envelope);
|
||||
}
|
||||
|
||||
private static Map<String, Object> location(EventInput.Location location) {
|
||||
var value = new LinkedHashMap<String, Object>();
|
||||
value.put("world_id", location.worldId().toString());
|
||||
value.put("world_name", location.worldName());
|
||||
value.put("x", location.x());
|
||||
value.put("y", location.y());
|
||||
value.put("z", location.z());
|
||||
value.put("captured_at", location.capturedAt().toString());
|
||||
value.put("quality", location.quality());
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override public void close() {
|
||||
if (closing) return;
|
||||
closing = true;
|
||||
try {
|
||||
if(!started.get()){worker.shutdown();if(worker.awaitTermination(5,TimeUnit.SECONDS)&&pendingEmpty())Files.deleteIfExists(activeBoot);return;}
|
||||
var stopped = submitClosing(lifecycle("game.stopped", "stopped"));
|
||||
worker.shutdown();
|
||||
var delivery = stopped.get(5, TimeUnit.SECONDS);
|
||||
if (!worker.awaitTermination(5, TimeUnit.SECONDS)) diagnostic.accept("Fantasy Stick event shutdown timed out");
|
||||
if(delivery!=Delivery.EXPORTED)degradedDiagnostic("Fantasy Stick stop event was not exported; incomplete lifetime evidence was retained");
|
||||
if (delivery == Delivery.EXPORTED && pendingEmpty()) Files.deleteIfExists(activeBoot);
|
||||
} catch (Exception failure) {
|
||||
diagnostic.accept("Fantasy Stick event shutdown failed: " + failure.getClass().getSimpleName());
|
||||
worker.shutdown();
|
||||
} finally {
|
||||
try { writerLock.release(); } catch (IOException ignored) { }
|
||||
try { lockChannel.close(); } catch (IOException ignored) { }
|
||||
}
|
||||
}
|
||||
|
||||
private boolean pendingEmpty() throws IOException {
|
||||
try (var files = Files.list(pending)) { return files.noneMatch(path -> path.getFileName().toString().endsWith(".pending")); }
|
||||
}
|
||||
|
||||
/** Small protected JSON encoder; values are immutable event snapshots, never arbitrary objects. */
|
||||
static final class Json {
|
||||
private Json() { }
|
||||
static String encode(Object value) {
|
||||
var output = new StringBuilder();
|
||||
append(output, value);
|
||||
return output.toString();
|
||||
}
|
||||
private static void append(StringBuilder output, Object value) {
|
||||
if (value == null) output.append("null");
|
||||
else if (value instanceof String text) string(output, text);
|
||||
else if (value instanceof UUID || value instanceof java.time.temporal.TemporalAccessor) string(output, value.toString());
|
||||
else if (value instanceof Boolean bool) output.append(bool);
|
||||
else if (value instanceof Number number) number(output, number);
|
||||
else if (value instanceof Map<?, ?> map) object(output, map);
|
||||
else if (value instanceof Collection<?> collection) array(output, collection);
|
||||
else throw new IllegalArgumentException("Unsupported event value " + value.getClass().getName());
|
||||
}
|
||||
private static void object(StringBuilder output, Map<?, ?> map) {
|
||||
output.append('{');
|
||||
boolean comma = false;
|
||||
for (var entry : map.entrySet()) {
|
||||
if (!(entry.getKey() instanceof String key)) throw new IllegalArgumentException("Non-string event key");
|
||||
if (comma) output.append(',');
|
||||
string(output, key); output.append(':'); append(output, entry.getValue()); comma = true;
|
||||
}
|
||||
output.append('}');
|
||||
}
|
||||
private static void array(StringBuilder output, Collection<?> values) {
|
||||
output.append('['); boolean comma = false;
|
||||
for (var value : values) { if (comma) output.append(','); append(output, value); comma = true; }
|
||||
output.append(']');
|
||||
}
|
||||
private static void number(StringBuilder output, Number number) {
|
||||
if (number instanceof Double doubleValue && !Double.isFinite(doubleValue)
|
||||
|| number instanceof Float floatValue && !Float.isFinite(floatValue)) {
|
||||
throw new IllegalArgumentException("Non-finite event number");
|
||||
}
|
||||
output.append(number);
|
||||
}
|
||||
private static void string(StringBuilder output, String text) {
|
||||
output.append('"');
|
||||
for (int index = 0; index < text.length(); index++) {
|
||||
char value = text.charAt(index);
|
||||
switch (value) {
|
||||
case '"' -> output.append("\\\"");
|
||||
case '\\' -> output.append("\\\\");
|
||||
case '\b' -> output.append("\\b");
|
||||
case '\f' -> output.append("\\f");
|
||||
case '\n' -> output.append("\\n");
|
||||
case '\r' -> output.append("\\r");
|
||||
case '\t' -> output.append("\\t");
|
||||
default -> {
|
||||
if (value < 0x20 || Character.isSurrogate(value)
|
||||
&& (Character.isHighSurrogate(value)
|
||||
? index + 1 >= text.length() || !Character.isLowSurrogate(text.charAt(index + 1))
|
||||
: index == 0 || !Character.isHighSurrogate(text.charAt(index - 1)))) {
|
||||
output.append(String.format("\\u%04x", (int) value));
|
||||
} else output.append(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
output.append('"');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user