Files
purpur-fantasy-stick/src/main/java/games/dmg/fantasystick/events/RecipeDiscoveryEventBridge.java
T
dmg 3f104cb0e2
Release / release (push) Successful in 14m50s
feat(events): record native recipe discovery
2026-09-25 10:07:18 -04:00

224 lines
11 KiB
Java

package games.dmg.fantasystick.events;
import java.io.ByteArrayOutputStream;
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.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import org.bukkit.entity.Player;
/** An acknowledged native discovery has one recoverable, account-keyed event intent. */
public final class RecipeDiscoveryEventBridge implements AutoCloseable {
private static final String RECIPE = "fantasystick:character_sheet";
private static final int MAX_BYTES = 16_384;
private final Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink;
private final Clock clock;
private final Path pending;
private final Consumer<Throwable> failures;
private final ExecutorService worker = Executors.newSingleThreadExecutor(task ->
new Thread(task, "fantasy-recipe-discovery-events"));
public RecipeDiscoveryEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
Clock clock, Path dataFolder, Consumer<Throwable> failures) {
this.sink = Objects.requireNonNull(sink);
this.clock = Objects.requireNonNull(clock);
this.pending = Objects.requireNonNull(dataFolder).toAbsolutePath().resolve("recipe-event-intents");
this.failures = Objects.requireNonNull(failures);
}
public void discovered(Player player, String trigger, int notifications) {
try {
var record = capture(player, trigger, notifications > 0);
worker.execute(() -> {
try { publish(write(record)); }
catch (IOException | RuntimeException failure) { report(failure); }
});
} catch (RuntimeException failure) { report(failure); }
}
/** Called only after the shared writer's startup recovery is ready. */
public void replay() {
try {
worker.execute(() -> {
try {
if (!Files.exists(pending, LinkOption.NOFOLLOW_LINKS)) return;
if (!Files.isDirectory(pending, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe recipe event intents");
try (var entries = Files.list(pending)) {
for (var path : entries.filter(p -> p.getFileName().toString().endsWith(".pending")).sorted().toList()) {
try { publish(read(path)); }
catch (IOException | RuntimeException failure) { report(failure); }
}
}
} catch (IOException | RuntimeException failure) { report(failure); }
});
} catch (RuntimeException failure) { report(failure); }
}
public void failed(Player player, String trigger, String reason) {
try {
var action = UUID.randomUUID();
var context = context(player);
emit(new EventInput(UUID.nameUUIDFromBytes(("fantasystick:recipe:" + action + ":failed")
.getBytes(StandardCharsets.UTF_8)), action, clock.instant(), "action.resolved", context,
Map.of("action_kind", "recipe_discovery", "recipe_id", RECIPE, "trigger", trigger,
"outcome", "failed", "reason", reason)));
} catch (RuntimeException failure) { report(failure); }
}
private record Record(UUID account, UUID action, Instant time, String name, String trigger,
boolean notification, EventInput.Location location) { }
private Record capture(Player player, String trigger, boolean notification) {
var context = context(player);
return new Record(context.playerId(), id(context.playerId()), clock.instant(), context.playerName(),
trigger, notification, context.location());
}
private EventInput.Context context(Player player) {
var location = player.getLocation();
EventInput.Location where = location == null || location.getWorld() == null ? null
: new EventInput.Location(location.getWorld().getUID(), location.getWorld().getName(),
location.getX(), location.getY(), location.getZ(), clock.instant(), "exact");
return new EventInput.Context(player.getUniqueId(), player.getName(), null, null, null, where);
}
private void publish(Record record) {
var fields = new LinkedHashMap<String, Object>();
fields.put("action_kind", "recipe_discovery");
fields.put("recipe_id", RECIPE);
fields.put("recipe_category", "misc");
fields.put("trigger", record.trigger());
fields.put("outcome", "acknowledged");
fields.put("first_discovery_notification", record.notification());
var input = new EventInput(UUID.nameUUIDFromBytes(("fantasystick:recipe:" + record.action()
+ ":recipe.discovered").getBytes(StandardCharsets.UTF_8)), record.action(), record.time(),
"recipe.discovered", new EventInput.Context(record.account(), record.name(), null, null, null,
record.location()), fields);
emit(input).whenComplete((delivery, failure) -> {
if (failure != null) { report(failure); return; }
if (delivery == LocalEventLog.Delivery.REJECTED) return;
try {
if (Files.deleteIfExists(file(record.account()))) forceDirectory();
} catch (IOException deleteFailure) { report(deleteFailure); }
});
}
private CompletionStage<LocalEventLog.Delivery> emit(EventInput input) {
try { return sink.apply(input); }
catch (RuntimeException failure) {
report(failure);
return java.util.concurrent.CompletableFuture.completedStage(LocalEventLog.Delivery.REJECTED);
}
}
private Path file(UUID account) { return pending.resolve(account + ".pending"); }
private Record write(Record record) throws IOException {
if (Files.exists(pending, LinkOption.NOFOLLOW_LINKS)
&& !Files.isDirectory(pending, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe recipe event intents");
Files.createDirectories(pending);
Path target = file(record.account());
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
if (!Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe recipe event intent");
return read(target); // Preserve the first native acknowledgment and its original identity.
}
var values = new Properties();
values.setProperty("account", record.account().toString());
values.setProperty("action", record.action().toString());
values.setProperty("time", record.time().toString());
values.setProperty("name", record.name());
values.setProperty("trigger", record.trigger());
values.setProperty("notification", Boolean.toString(record.notification()));
if (record.location() != null) {
var location = record.location();
values.setProperty("world", location.worldId().toString());
values.setProperty("world_name", location.worldName());
values.setProperty("x", Double.toString(location.x()));
values.setProperty("y", Double.toString(location.y()));
values.setProperty("z", Double.toString(location.z()));
values.setProperty("location_time", location.capturedAt().toString());
}
var output = new ByteArrayOutputStream();
values.store(output, "acknowledged native recipe discovery");
var bytes = output.toByteArray();
if (bytes.length > MAX_BYTES) throw new IOException("Recipe event intent too large");
Path temporary = Files.createTempFile(pending, ".recipe-", ".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 record;
}
private void forceDirectory() throws IOException {
try (var channel = FileChannel.open(pending, StandardOpenOption.READ)) { channel.force(true); }
}
private Record read(Path path) throws IOException {
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe recipe event intent");
var values = 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("Recipe event intent too large");
values.load(new java.io.ByteArrayInputStream(bytes));
}
try {
var account = UUID.fromString(values.getProperty("account"));
var action = UUID.fromString(values.getProperty("action"));
if (!path.equals(file(account)) || !action.equals(id(account))) throw new IOException("Invalid recipe event identity");
EventInput.Location location = values.containsKey("world")
? new EventInput.Location(UUID.fromString(values.getProperty("world")), values.getProperty("world_name"),
Double.parseDouble(values.getProperty("x")), Double.parseDouble(values.getProperty("y")),
Double.parseDouble(values.getProperty("z")), Instant.parse(values.getProperty("location_time")), "exact")
: null;
var trigger = values.getProperty("trigger");
if (!"join".equals(trigger) && !"enable_online".equals(trigger)) throw new IOException("Invalid recipe event trigger");
var notification = values.getProperty("notification");
if (!"true".equals(notification) && !"false".equals(notification)) throw new IOException("Invalid recipe notification");
return new Record(account, action, Instant.parse(values.getProperty("time")),
Objects.requireNonNull(values.getProperty("name")), trigger, Boolean.parseBoolean(notification), location);
} catch (RuntimeException invalid) { throw new IOException("Invalid recipe event intent", invalid); }
}
public static UUID id(UUID player) {
return UUID.nameUUIDFromBytes(("fantasystick:recipe:character_sheet:" + player)
.getBytes(StandardCharsets.UTF_8));
}
private void report(Throwable failure) {
try { failures.accept(failure); } catch (RuntimeException ignored) { }
}
@Override public void close() {
worker.shutdown();
try {
if (!worker.awaitTermination(5, TimeUnit.SECONDS)) report(new IOException("Recipe event intents did not drain"));
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt(); report(interrupted);
}
}
}