444 lines
23 KiB
Java
444 lines
23 KiB
Java
package games.dmg.fantasystick.events;
|
|
|
|
import java.io.ByteArrayInputStream;
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.IOException;
|
|
import java.nio.ByteBuffer;
|
|
import java.nio.channels.FileChannel;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.DirectoryStream;
|
|
import java.util.Iterator;
|
|
import java.nio.file.LinkOption;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.StandardCopyOption;
|
|
import java.nio.file.StandardOpenOption;
|
|
import java.time.Instant;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.Properties;
|
|
import java.util.Set;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.CompletableFuture;
|
|
import java.util.concurrent.CompletionStage;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.ArrayBlockingQueue;
|
|
import java.util.concurrent.RejectedExecutionException;
|
|
import java.util.concurrent.Semaphore;
|
|
import java.util.concurrent.ThreadPoolExecutor;
|
|
import java.util.concurrent.TimeUnit;
|
|
import java.util.function.Consumer;
|
|
import java.util.function.Function;
|
|
|
|
/** Per-feature recoverable intent for acknowledged domain outcomes. Never replays gameplay. */
|
|
final class FeatureEventOutbox implements AutoCloseable {
|
|
private static final int MAX_BYTES = 16_384;
|
|
// Shared internal safety envelope: queued snapshots AND unsettled sink callbacks across all owners.
|
|
private static final int MAX_HANDOFFS = 1024;
|
|
private static final Semaphore HANDOFFS = new Semaphore(MAX_HANDOFFS);
|
|
// One small control record per live feature owner, never per rejected observation or pending file.
|
|
private static final Semaphore OWNER_SLOTS = new Semaphore(MAX_HANDOFFS);
|
|
private static final Set<FeatureEventOutbox> OWNERS = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
|
private static final Object MAINTENANCE_LIFETIME = new Object();
|
|
private static java.util.concurrent.ScheduledExecutorService REPLAYS;
|
|
private static java.util.concurrent.ScheduledExecutorService DIAGNOSTICS;
|
|
|
|
private static void attach(FeatureEventOutbox owner) {
|
|
synchronized (MAINTENANCE_LIFETIME) {
|
|
OWNERS.add(owner);
|
|
if (REPLAYS == null) {
|
|
REPLAYS = maintenance("fantasy-feature-replay");
|
|
DIAGNOSTICS = maintenance("fantasy-feature-diagnostics");
|
|
REPLAYS.scheduleWithFixedDelay(() -> OWNERS.forEach(FeatureEventOutbox::continueReplay), 100, 100, TimeUnit.MILLISECONDS);
|
|
DIAGNOSTICS.scheduleWithFixedDelay(() -> OWNERS.forEach(FeatureEventOutbox::diagnose), 100, 100, TimeUnit.MILLISECONDS);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void detach(FeatureEventOutbox owner) {
|
|
synchronized (MAINTENANCE_LIFETIME) {
|
|
OWNERS.remove(owner);
|
|
if (OWNERS.isEmpty()) {
|
|
REPLAYS.shutdown(); DIAGNOSTICS.shutdown();
|
|
REPLAYS = null; DIAGNOSTICS = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static java.util.concurrent.ScheduledExecutorService maintenance(String name) {
|
|
return java.util.concurrent.Executors.newSingleThreadScheduledExecutor(task -> {
|
|
var thread = new Thread(task, name); thread.setDaemon(true); return thread;
|
|
});
|
|
}
|
|
|
|
static final class HandoffRejection extends RejectedExecutionException {
|
|
private static final long serialVersionUID = 1L;
|
|
private final long rejected, deferred;
|
|
HandoffRejection(long rejected, long deferred) {
|
|
super("Feature audit handoff: " + rejected + " observations rejected before durable acceptance; "
|
|
+ deferred + " replay passes deferred with durable intents retained");
|
|
this.rejected = rejected; this.deferred = deferred;
|
|
}
|
|
long rejectedCount() { return rejected; }
|
|
long deferredCount() { return deferred; }
|
|
}
|
|
private final Set<String> types;
|
|
private final Path directory;
|
|
private final Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink;
|
|
private final Consumer<Throwable> failures;
|
|
private final ExecutorService worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
|
|
new ArrayBlockingQueue<>(MAX_HANDOFFS), task -> new Thread(task, "fantasy-feature-event-intents"),
|
|
new ThreadPoolExecutor.AbortPolicy()) {
|
|
@Override protected void terminated() { closeReplayCursor(); }
|
|
};
|
|
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
|
private final Set<UUID> inFlight = java.util.concurrent.ConcurrentHashMap.newKeySet();
|
|
// 0 detached, 1 attached, 2 retiring, 3 registering: no caller waits for maintenance or I/O.
|
|
private final java.util.concurrent.atomic.AtomicInteger registration = new java.util.concurrent.atomic.AtomicInteger();
|
|
private final java.util.concurrent.atomic.AtomicBoolean closed = new java.util.concurrent.atomic.AtomicBoolean();
|
|
private final java.util.concurrent.atomic.AtomicBoolean replayQueued = new java.util.concurrent.atomic.AtomicBoolean();
|
|
private final java.util.concurrent.atomic.AtomicBoolean diagnosing = new java.util.concurrent.atomic.AtomicBoolean();
|
|
private final java.util.concurrent.atomic.AtomicBoolean closingDiagnosis = new java.util.concurrent.atomic.AtomicBoolean();
|
|
private final java.util.concurrent.atomic.AtomicLong rejected = new java.util.concurrent.atomic.AtomicLong();
|
|
private final java.util.concurrent.atomic.AtomicLong deferred = new java.util.concurrent.atomic.AtomicLong();
|
|
private final Object diagnosticFence = new Object();
|
|
private volatile long lastDiagnostic;
|
|
private volatile boolean replayRequested;
|
|
// The directory cursor is confined to the intent worker; it retains no materialized backlog.
|
|
private DirectoryStream<Path> replayFiles;
|
|
private Iterator<Path> replayPaths;
|
|
|
|
FeatureEventOutbox(Path data, String folder, Set<String> types,
|
|
Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
|
|
Consumer<Throwable> failures) {
|
|
if (!folder.matches("[a-z-]+")) throw new IllegalArgumentException("Unsafe event intent folder");
|
|
directory = data.toAbsolutePath().resolve(folder);
|
|
this.types = Set.copyOf(types);
|
|
this.sink = sink;
|
|
this.failures = failures;
|
|
if (!register()) throw new RejectedExecutionException("Feature audit owner capacity exhausted");
|
|
}
|
|
|
|
private boolean register() {
|
|
if (!registration.compareAndSet(0, 3)) return true;
|
|
if (!OWNER_SLOTS.tryAcquire()) { registration.set(0); return false; }
|
|
attach(this); registration.set(1); return true;
|
|
}
|
|
|
|
private void retire() {
|
|
if (!worker.isTerminated() || rejected.get() != 0 || deferred.get() != 0 || diagnosing.get()) return;
|
|
if (!registration.compareAndSet(1, 2)) return;
|
|
detach(this); OWNER_SLOTS.release(); registration.set(0);
|
|
// A producer seeing state 2 cannot reattach until removal finishes; its counts remain owned here.
|
|
if (rejected.get() != 0 || deferred.get() != 0) register();
|
|
}
|
|
|
|
private void rejectObservation() { rejected.incrementAndGet(); register(); }
|
|
|
|
private void diagnose() {
|
|
if (!diagnosing.compareAndSet(false, true)) return;
|
|
try {
|
|
long now = System.nanoTime();
|
|
if (!closingDiagnosis.getAndSet(false) && lastDiagnostic != 0
|
|
&& now - lastDiagnostic < TimeUnit.SECONDS.toNanos(1)) return;
|
|
long lost = rejected.getAndSet(0), delayed = deferred.getAndSet(0);
|
|
if (lost != 0 || delayed != 0) {
|
|
lastDiagnostic = now;
|
|
report(new HandoffRejection(lost, delayed));
|
|
}
|
|
} finally {
|
|
diagnosing.set(false);
|
|
synchronized (diagnosticFence) { diagnosticFence.notifyAll(); }
|
|
retire();
|
|
}
|
|
}
|
|
|
|
void accepted(EventInput event) {
|
|
if (!admit()) return;
|
|
try { worker.execute(() -> {
|
|
EventInput saved;
|
|
try { saved = write(event); }
|
|
catch (IOException | RuntimeException failure) { HANDOFFS.release(); report(failure); return; }
|
|
publish(saved); // The admission remains owned until delivery settles, not merely until dequeue.
|
|
}); } catch (RejectedExecutionException failure) { HANDOFFS.release(); rejectObservation(); }
|
|
}
|
|
|
|
private boolean admit() {
|
|
if (closed.get() || worker.isShutdown() || !HANDOFFS.tryAcquire()) {
|
|
rejectObservation();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
void replay() {
|
|
if (closed.get()) return;
|
|
replayRequested = true;
|
|
continueReplay();
|
|
}
|
|
|
|
private void continueReplay() {
|
|
if (!replayRequested || closed.get() || !replayQueued.compareAndSet(false, true)) return;
|
|
// The command and its next handoff both need a slot. Never wait or do caller-thread I/O.
|
|
if (HANDOFFS.availablePermits() < 2 || !HANDOFFS.tryAcquire()) {
|
|
replayQueued.set(false);
|
|
if (deferred.compareAndSet(0, 1)) register();
|
|
return;
|
|
}
|
|
try { worker.execute(this::replayBatch); }
|
|
catch (RejectedExecutionException failure) {
|
|
HANDOFFS.release(); replayQueued.set(false); deferred.compareAndSet(0, 1);
|
|
}
|
|
}
|
|
|
|
private void replayBatch() {
|
|
try {
|
|
if (replayFiles == null) {
|
|
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { replayRequested = false; return; }
|
|
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe character event directory");
|
|
replayFiles = Files.newDirectoryStream(directory, "*.pending");
|
|
replayPaths = replayFiles.iterator();
|
|
}
|
|
while (replayPaths.hasNext()) {
|
|
if (!HANDOFFS.tryAcquire()) {
|
|
deferred.compareAndSet(0, 1);
|
|
return; // Resume this same bounded cursor after any owner's acknowledgment releases capacity.
|
|
}
|
|
EventInput saved;
|
|
try { saved = read(replayPaths.next()); }
|
|
catch (IOException | RuntimeException failure) { HANDOFFS.release(); report(failure); continue; }
|
|
publish(saved);
|
|
}
|
|
replayRequested = false;
|
|
} catch (IOException | RuntimeException failure) { replayRequested = false; report(failure); }
|
|
finally {
|
|
if (!replayRequested || closed.get()) closeReplayCursor();
|
|
replayQueued.set(false); HANDOFFS.release();
|
|
}
|
|
}
|
|
|
|
private void closeReplayCursor() {
|
|
if (replayFiles == null) return;
|
|
try { replayFiles.close(); } catch (IOException failure) { report(failure); }
|
|
finally { replayFiles = null; replayPaths = null; }
|
|
}
|
|
|
|
private Path path(EventInput event) { return directory.resolve(event.id() + ".pending"); }
|
|
|
|
private EventInput write(EventInput event) throws IOException {
|
|
if (!types.contains(event.type())) throw new IOException("Unsupported character intent type");
|
|
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)
|
|
&& !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe character event directory");
|
|
Files.createDirectories(directory);
|
|
var target = path(event);
|
|
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) return read(target);
|
|
var fields = new Properties();
|
|
fields.setProperty("id", event.id().toString());
|
|
fields.setProperty("action", event.actionId().toString());
|
|
fields.setProperty("time", event.time().toString());
|
|
fields.setProperty("type", event.type());
|
|
var context = event.context();
|
|
if (context != null) {
|
|
fields.setProperty("player", context.playerId().toString());
|
|
fields.setProperty("player_name", context.playerName());
|
|
}
|
|
if (context != null && context.characterId() != null) {
|
|
fields.setProperty("character", context.characterId().toString());
|
|
fields.setProperty("character_name", context.characterName());
|
|
fields.setProperty("session", context.sessionId().toString());
|
|
}
|
|
if (context != null && context.location() != null) {
|
|
var location = context.location();
|
|
fields.setProperty("world", location.worldId().toString());
|
|
fields.setProperty("world_name", location.worldName());
|
|
fields.setProperty("x", Double.toString(location.x()));
|
|
fields.setProperty("y", Double.toString(location.y()));
|
|
fields.setProperty("z", Double.toString(location.z()));
|
|
fields.setProperty("captured_at", location.capturedAt().toString());
|
|
fields.setProperty("quality", location.quality());
|
|
}
|
|
event.data().forEach((key, value) -> {
|
|
if (value instanceof java.util.Map<?, ?> nested) {
|
|
if (key.contains(".")) throw new IllegalArgumentException("Unsafe nested feature intent key");
|
|
nested.forEach((name, part) -> {
|
|
if (!(name instanceof String child) || child.contains("."))
|
|
throw new IllegalArgumentException("Unsafe nested feature intent key");
|
|
encode(fields, "data." + key + "." + child, part);
|
|
});
|
|
} else encode(fields, "data." + key, value);
|
|
});
|
|
var output = new ByteArrayOutputStream();
|
|
fields.store(output, "acknowledged character identity event");
|
|
var bytes = output.toByteArray();
|
|
if (bytes.length > MAX_BYTES) throw new IOException("Character event intent too large");
|
|
var temporary = Files.createTempFile(directory, ".identity-", ".tmp");
|
|
try {
|
|
try (var channel = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
|
var buffer = ByteBuffer.wrap(bytes);
|
|
while (buffer.hasRemaining()) channel.write(buffer);
|
|
channel.force(true);
|
|
}
|
|
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
|
forceDirectory();
|
|
} finally { Files.deleteIfExists(temporary); }
|
|
return event;
|
|
}
|
|
|
|
private static void encode(Properties fields, String key, Object value) {
|
|
if (value instanceof String text) fields.setProperty(key, "s" + text);
|
|
else if (value instanceof Boolean bool) fields.setProperty(key, "b" + bool);
|
|
else if (value instanceof Integer number) fields.setProperty(key, "i" + number);
|
|
else if (value instanceof Double number && Double.isFinite(number)) fields.setProperty(key, "d" + number);
|
|
else if (value instanceof java.util.List<?> list && list.stream().allMatch(item -> item instanceof String text
|
|
&& (text.equals("hotbar") || text.equals("armor"))))
|
|
fields.setProperty(key, "l" + String.join(",", list.stream().map(String.class::cast).toList()));
|
|
else if (value instanceof java.util.List<?> list)
|
|
fields.setProperty(key, "j" + new com.google.gson.Gson().toJson(list));
|
|
else throw new IllegalArgumentException("Unsupported feature intent value");
|
|
}
|
|
|
|
private EventInput read(Path path) throws IOException {
|
|
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe character event intent");
|
|
var fields = new Properties();
|
|
try (var input = Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS)) {
|
|
var bytes = input.readNBytes(MAX_BYTES + 1);
|
|
if (bytes.length > MAX_BYTES) throw new IOException("Character event intent too large");
|
|
fields.load(new ByteArrayInputStream(bytes));
|
|
}
|
|
try {
|
|
var id = UUID.fromString(fields.getProperty("id"));
|
|
var action = UUID.fromString(fields.getProperty("action"));
|
|
var type = fields.getProperty("type");
|
|
if (!path.equals(directory.resolve(id + ".pending")) || !types.contains(type))
|
|
throw new IOException("Invalid character event intent identity");
|
|
EventInput.Location location = fields.containsKey("world")
|
|
? new EventInput.Location(UUID.fromString(fields.getProperty("world")), fields.getProperty("world_name"),
|
|
Double.parseDouble(fields.getProperty("x")), Double.parseDouble(fields.getProperty("y")),
|
|
Double.parseDouble(fields.getProperty("z")), Instant.parse(fields.getProperty("captured_at")),
|
|
fields.getProperty("quality")) : null;
|
|
var character = fields.containsKey("character") ? UUID.fromString(fields.getProperty("character")) : null;
|
|
if (!fields.containsKey("player") && (character != null || fields.containsKey("session") || location != null))
|
|
throw new IOException("Unbound event context");
|
|
var context = fields.containsKey("player")
|
|
? new EventInput.Context(UUID.fromString(fields.getProperty("player")),
|
|
fields.getProperty("player_name"), character, fields.getProperty("character_name"),
|
|
fields.containsKey("session") ? UUID.fromString(fields.getProperty("session")) : null, location)
|
|
: null;
|
|
var data = new LinkedHashMap<String, Object>();
|
|
var nested = new LinkedHashMap<String, java.util.Map<String, Object>>();
|
|
for (var key : fields.stringPropertyNames()) if (key.startsWith("data.")) {
|
|
var value = fields.getProperty(key);
|
|
if (value.isEmpty()) throw new IOException("Invalid character event value");
|
|
var decoded = switch (value.charAt(0)) {
|
|
case 's' -> value.substring(1);
|
|
case 'b' -> {
|
|
if (!value.equals("btrue") && !value.equals("bfalse")) throw new IOException("Invalid boolean");
|
|
yield Boolean.valueOf(value.substring(1));
|
|
}
|
|
case 'i' -> Integer.valueOf(value.substring(1));
|
|
case 'd' -> {
|
|
var number = Double.valueOf(value.substring(1));
|
|
if (!Double.isFinite(number)) throw new IOException("Non-finite event coordinate");
|
|
yield number;
|
|
}
|
|
case 'l' -> {
|
|
var encoded = value.substring(1);
|
|
var list = encoded.isEmpty() ? java.util.List.<String>of() : java.util.List.of(encoded.split(","));
|
|
if (!list.stream().allMatch(item -> item.equals("hotbar") || item.equals("armor")))
|
|
throw new IOException("Invalid slot class");
|
|
yield list;
|
|
}
|
|
case 'j' -> {
|
|
var parsed = com.google.gson.JsonParser.parseString(value.substring(1));
|
|
if (!parsed.isJsonArray()) throw new IOException("Invalid event collection");
|
|
yield decodeCollection(parsed, 0);
|
|
}
|
|
default -> throw new IOException("Invalid feature event value type");
|
|
};
|
|
var name = key.substring(5);
|
|
var separator = name.indexOf('.');
|
|
if (separator < 0) data.put(name, decoded);
|
|
else {
|
|
if (separator == 0 || separator == name.length() - 1 || name.indexOf('.', separator + 1) >= 0)
|
|
throw new IOException("Invalid nested feature intent key");
|
|
nested.computeIfAbsent(name.substring(0, separator), ignored -> new LinkedHashMap<>())
|
|
.put(name.substring(separator + 1), decoded);
|
|
}
|
|
}
|
|
nested.forEach((key, value) -> {
|
|
if (data.putIfAbsent(key, value) != null) throw new IllegalArgumentException("Conflicting feature intent key");
|
|
});
|
|
return new EventInput(id, action, Instant.parse(fields.getProperty("time")), type, context, data);
|
|
} catch (RuntimeException failure) { throw new IOException("Invalid character event intent", failure); }
|
|
}
|
|
|
|
private static Object decodeCollection(com.google.gson.JsonElement value, int depth) throws IOException {
|
|
if (depth > 8 || value.isJsonNull()) throw new IOException("Unsafe event collection");
|
|
if (value.isJsonArray()) {
|
|
var list = new java.util.ArrayList<>();
|
|
for (var item : value.getAsJsonArray()) list.add(decodeCollection(item, depth + 1));
|
|
return java.util.List.copyOf(list);
|
|
}
|
|
if (value.isJsonObject()) {
|
|
var map = new LinkedHashMap<String, Object>();
|
|
for (var entry : value.getAsJsonObject().entrySet())
|
|
map.put(entry.getKey(), decodeCollection(entry.getValue(), depth + 1));
|
|
return java.util.Map.copyOf(map);
|
|
}
|
|
var primitive = value.getAsJsonPrimitive();
|
|
if (primitive.isBoolean()) return primitive.getAsBoolean();
|
|
if (primitive.isString()) return primitive.getAsString();
|
|
if (primitive.isNumber()) {
|
|
var number = primitive.getAsDouble();
|
|
if (!Double.isFinite(number)) throw new IOException("Non-finite event collection number");
|
|
return number;
|
|
}
|
|
throw new IOException("Unsupported event collection value");
|
|
}
|
|
|
|
private void publish(EventInput event) {
|
|
if (!inFlight.add(event.id())) { HANDOFFS.release(); return; }
|
|
try { sink.apply(event).whenComplete((delivery, failure) -> {
|
|
try {
|
|
if (failure != null) { report(failure); return; }
|
|
if (delivery == LocalEventLog.Delivery.REJECTED) return;
|
|
try { if (Files.deleteIfExists(path(event))) forceDirectory(); }
|
|
catch (IOException error) { report(error); }
|
|
} finally { inFlight.remove(event.id()); HANDOFFS.release(); }
|
|
}); } catch (RuntimeException failure) {
|
|
inFlight.remove(event.id());
|
|
HANDOFFS.release();
|
|
report(failure);
|
|
}
|
|
}
|
|
|
|
private void forceDirectory() throws IOException {
|
|
try (var channel = FileChannel.open(directory, StandardOpenOption.READ)) { channel.force(true); }
|
|
}
|
|
|
|
private void report(Throwable error) {
|
|
try { failures.accept(error); } catch (RuntimeException ignored) { }
|
|
}
|
|
|
|
@Override public void close() {
|
|
if (!closed.compareAndSet(false, true)) return;
|
|
closingDiagnosis.set(true);
|
|
worker.shutdown();
|
|
CompletableFuture.runAsync(() -> {
|
|
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
|
|
try {
|
|
if (!worker.awaitTermination(5, TimeUnit.SECONDS)) report(new IOException("Character event intents did not drain"));
|
|
synchronized (diagnosticFence) {
|
|
while (rejected.get() != 0 || deferred.get() != 0 || diagnosing.get()) {
|
|
long remaining = deadline - System.nanoTime();
|
|
if (remaining <= 0) break; // Bounded shutdown attempt; maintenance retains the aggregate diagnosis.
|
|
TimeUnit.NANOSECONDS.timedWait(diagnosticFence, remaining);
|
|
}
|
|
}
|
|
} catch (InterruptedException interrupted) {
|
|
Thread.currentThread().interrupt(); report(interrupted);
|
|
} finally { retire(); drained.complete(null); }
|
|
});
|
|
}
|
|
|
|
CompletionStage<Void> drained() { return drained; }
|
|
}
|