Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/events/LocalEventLog.java
T
dmg a19909f152
CI / build (push) Successful in 43s
CI / build (pull_request) Successful in 1m1s
fix(events): recover partial appends without restarting
2026-10-08 09:26:27 -04:00

492 lines
26 KiB
Java

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 Path damagedSegment;
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) {
recovered |= recoverInterruptedTail(path);
}
return recovered;
}
/** Quarantine must be forced before truncation; failure leaves pending work and repair state intact. */
private boolean recoverInterruptedTail(Path path) throws IOException {
if (Files.isSymbolicLink(path)) throw new IOException("Symbolic link in Fantasy Stick event segments");
var bytes = Files.readAllBytes(path);
int prefix = 0;
int 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) return false;
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 true;
}
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 {
if (damagedSegment != null) {
recoverInterruptedTail(damagedSegment);
damagedSegment = null;
}
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);
} catch (IOException failure) {
// Even open/force/close failures can leave uncertain bytes. Never reuse this
// segment or acknowledge pending work until its tail has been repaired.
damagedSegment = segment;
segment = null;
segmentDate = null;
segmentBytes = 0;
throw failure;
}
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 {
var claimed = data.get("actor_kind");
data.put("actor_kind", "console".equals(claimed) || "command_block".equals(claimed)
? claimed : "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('"');
}
}
}