This commit is contained in:
1 parent
715f3cc6ef
commit
7dc23161a3
21 files changed
+1812
-27
No files matched your search
@@ -225,6 +225,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private java.util.concurrent.CompletionStage<Void> partyCapacityAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
|
||||
private games.dmg.fantasystick.events.SheetResourcePackEventBridge sheetResourcePackEvents;
|
||||
private java.util.concurrent.CompletionStage<Void> sheetResourcePackAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
|
||||
private games.dmg.fantasystick.events.AdminCoinsEventBridge adminCoinsEvents;
|
||||
private java.util.concurrent.CompletionStage<Void> adminCoinsAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
|
||||
private games.dmg.fantasystick.events.AdminExperienceEventBridge adminExperienceEvents;
|
||||
private java.util.concurrent.CompletionStage<Void> adminExperienceAuditDrain = java.util.concurrent.CompletableFuture.completedFuture(null);
|
||||
private games.dmg.fantasystick.events.CharacterIdentityEventBridge identityAuditEvents;
|
||||
@@ -740,6 +742,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
problem -> getLogger().log(Level.WARNING,
|
||||
"Admin experience grant for character " + problem.character(), problem.cause()), particleDelivery);
|
||||
admin.attachExperienceGrant(grantService);
|
||||
var coinsService = new games.dmg.fantasystick.session.AdminCharacterCoins(characters, sessions, nextTick);
|
||||
admin.attachCharacterCoins(coinsService);
|
||||
admin.attachSwitchDelay(switchDelaySettings);
|
||||
admin.attachRoleplaySettings(roleplaySettings);
|
||||
admin.attachPartySettings(partySettings);
|
||||
@@ -1015,6 +1019,10 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
eventLog::emit, Clock.systemUTC(), getDataFolder().toPath(),
|
||||
failure -> getLogger().log(Level.WARNING, "Admin experience event intent failed", failure));
|
||||
grantService.attachEvents(adminExperienceEvents);
|
||||
adminCoinsEvents = new games.dmg.fantasystick.events.AdminCoinsEventBridge(eventLog::emit,
|
||||
Clock.systemUTC(), getDataFolder().toPath(), sessions,
|
||||
failure -> getLogger().log(Level.WARNING, "Admin coins event intent failed", failure));
|
||||
coinsService.attachEvents(adminCoinsEvents);
|
||||
var identitySessions = sessions;
|
||||
identityAuditEvents = new games.dmg.fantasystick.events.CharacterIdentityEventBridge(
|
||||
eventLog::emit, Clock.systemUTC(), getDataFolder().toPath(),
|
||||
@@ -1158,6 +1166,11 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if (failure != null) getLogger().log(Level.WARNING, "Previous sheet pack event intent drain failed", failure);
|
||||
if (replaySheetPackEvents != null) replaySheetPackEvents.replay();
|
||||
});
|
||||
var replayCoinsEvents = adminCoinsEvents;
|
||||
adminCoinsAuditDrain.whenComplete((ignored, failure) -> {
|
||||
if (failure != null) getLogger().log(Level.WARNING, "Previous admin coins intent drain failed", failure);
|
||||
if (replayCoinsEvents != null) replayCoinsEvents.replay();
|
||||
});
|
||||
var replayGrantEvents = adminExperienceEvents;
|
||||
adminExperienceAuditDrain.whenComplete((ignored, failure) -> {
|
||||
if (failure != null) getLogger().log(Level.WARNING, "Previous admin experience intent drain failed", failure);
|
||||
@@ -1322,6 +1335,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingRoleplayEvents = roleplayAvailabilityEvents; roleplayAvailabilityEvents = null;
|
||||
var closingPartyCapacityEvents = partyCapacityEvents; partyCapacityEvents = null;
|
||||
var closingSheetPackEvents = sheetResourcePackEvents; sheetResourcePackEvents = null;
|
||||
var closingCoinsEvents = adminCoinsEvents; adminCoinsEvents = null;
|
||||
var closingGrantEvents = adminExperienceEvents; adminExperienceEvents = null;
|
||||
var closingKnockbackEvents = stickKnockbackEvents; stickKnockbackEvents = null;
|
||||
var closingHardMobXpEvents = hardMobXpAuditEvents; hardMobXpAuditEvents = null;
|
||||
@@ -1688,6 +1702,14 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
return null;
|
||||
}).thenCompose(ignored -> closingSheetPackEvents.drained());
|
||||
});
|
||||
if (closingCoinsEvents != null) cleanup("admin coins event intent drain", () -> {
|
||||
var storageDrained = closingCharacters == null ? java.util.concurrent.CompletableFuture.<Void>completedFuture(null)
|
||||
: closingCharacters.drained();
|
||||
adminCoinsAuditDrain = storageDrained.handle((ignored, failure) -> {
|
||||
if (failure != null) getLogger().log(Level.WARNING, "Character drain before coins events failed", failure);
|
||||
closingCoinsEvents.close(); return null;
|
||||
}).thenCompose(ignored -> closingCoinsEvents.drained());
|
||||
});
|
||||
if (closingGrantEvents != null) cleanup("admin experience event intent drain", () -> {
|
||||
var storageDrained = closingCharacters == null
|
||||
? java.util.concurrent.CompletableFuture.<Void>completedFuture(null)
|
||||
|
||||
@@ -169,6 +169,9 @@ public final class AdminActionEventBridge implements AutoCloseable {
|
||||
Map<String, Object> safeArgs = Map.of();
|
||||
if (permitted && valid && (route.equals("inspect") || route.equals("recover"))) {
|
||||
safeArgs = Map.of("player_id", UUID.fromString(args[1]).toString());
|
||||
} else if (permitted && valid && route.equals("character") && args[1].equals("coins")) {
|
||||
safeArgs = Map.of("character_id", UUID.fromString(args[2]).toString(),
|
||||
"delta", new java.math.BigInteger(args[3]).toString());
|
||||
} else if (permitted && valid && route.equals("config")
|
||||
&& configurationKeys.contains(args[1])) {
|
||||
var typed = new LinkedHashMap<String, Object>();
|
||||
@@ -200,6 +203,12 @@ public final class AdminActionEventBridge implements AutoCloseable {
|
||||
if (route.equals("adventure")) return (length == 2 || length == 3)
|
||||
&& args[1].equals("reroll") && (length == 2 || args[2].equals("confirm"));
|
||||
if (length < 2) return false;
|
||||
if (route.equals("character") && args[1].equals("coins")) {
|
||||
if (length != 4 || !args[3].matches("[+-]?[0-9]+")) return false;
|
||||
try { return UUID.fromString(args[2]).toString().equalsIgnoreCase(args[2])
|
||||
&& new java.math.BigInteger(args[3]).signum() != 0; }
|
||||
catch (IllegalArgumentException invalid) { return false; }
|
||||
}
|
||||
return switch (route) {
|
||||
case "character" -> Set.of("find", "show", "recover", "view").contains(args[1]);
|
||||
case "adventure-site" -> Set.of("list", "place", "fishing", "mode", "remove", "teleport").contains(args[1]);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package games.dmg.fantasystick.events;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Independent feature outbox: only acknowledged administrator balance adjustments. */
|
||||
public final class AdminCoinsEventBridge implements AutoCloseable {
|
||||
public record Intent(UUID operation, UUID action, Instant time, String actorKind, EventInput.Context actor) { }
|
||||
private final Clock clock;
|
||||
private final EquipmentSessions sessions;
|
||||
private final FeatureEventOutbox outbox;
|
||||
public AdminCoinsEventBridge(Function<EventInput, CompletionStage<LocalEventLog.Delivery>> sink,
|
||||
Clock clock, Path data, EquipmentSessions sessions, Consumer<Throwable> failures) {
|
||||
this.clock = clock; this.sessions = sessions;
|
||||
outbox = new FeatureEventOutbox(data, "admin-coins-event-intents", Set.of("character.coins_adjusted"), sink, failures);
|
||||
}
|
||||
public Intent capture(CommandSender sender, UUID action) {
|
||||
EventInput.Context actor = null;
|
||||
if (sender instanceof Player player) {
|
||||
var active = sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);
|
||||
var record = active == null ? null : sessions.currentRecord(active).orElse(null);
|
||||
EventInput.Location location = null;
|
||||
try {
|
||||
var place = player.getLocation();
|
||||
if (place != null && place.getWorld() != null) location = new EventInput.Location(place.getWorld().getUID(),
|
||||
place.getWorld().getName(), place.getX(), place.getY(), place.getZ(), clock.instant(), "exact");
|
||||
} catch (RuntimeException unavailable) { /* Optional actor location is never mutation authority. */ }
|
||||
actor = new EventInput.Context(player.getUniqueId(), player.getName(), record == null ? null : record.id(),
|
||||
record == null ? null : record.name(), active == null ? null : active.session(), location);
|
||||
}
|
||||
return new Intent(UUID.randomUUID(), action, clock.instant(), sender instanceof Player ? "player" : "console", actor);
|
||||
}
|
||||
public void adjusted(Intent intent, CharacterRecord before, CharacterRecord after, BigInteger delta,
|
||||
String targetState, String sync) {
|
||||
var values = new LinkedHashMap<String, Object>();
|
||||
values.put("operation_id", intent.operation().toString());
|
||||
if (intent.action() != null) values.put("admin_action_id", intent.action().toString());
|
||||
values.put("actor_kind", intent.actorKind());
|
||||
values.put("target_character_id", after.id().toString()); values.put("target_character_name", after.name());
|
||||
values.put("delta", delta.toString());
|
||||
values.put("before_coins", before.coins().toString()); values.put("after_coins", after.coins().toString());
|
||||
values.put("before_revision", before.revision().toString()); values.put("after_revision", after.revision().toString());
|
||||
values.put("target_state", targetState); values.put("session_sync", sync);
|
||||
var location = intent.actor() == null ? null : intent.actor().location();
|
||||
values.put("location_status", intent.actor() == null ? "not_applicable" : location == null ? "unavailable" : "captured");
|
||||
if (location != null) values.put("location", Map.of("world_id", location.worldId().toString(),
|
||||
"world_name", location.worldName(), "x", location.x(), "y", location.y(), "z", location.z(),
|
||||
"captured_at", location.capturedAt().toString(), "quality", location.quality()));
|
||||
outbox.accepted(new EventInput(eventId(intent.operation()), intent.operation(), intent.time(),
|
||||
"character.coins_adjusted", intent.actor(), values));
|
||||
}
|
||||
public static UUID eventId(UUID operation) {
|
||||
return UUID.nameUUIDFromBytes(("fantasystick:admin-coins:" + operation).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
public void replay() { outbox.replay(); }
|
||||
public CompletionStage<Void> drained() { return outbox.drained(); }
|
||||
@Override public void close() { outbox.close(); }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
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.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Frozen operation proofs, independent of the bounded gameplay reward ledger. All access owns the records lock. */
|
||||
final class AdminCoinOperationStore {
|
||||
enum Phase { PREPARED, APPLIED, FAILED, UNCERTAIN }
|
||||
record Proof(UUID operation, BigInteger delta, CharacterRecord before, CharacterRecord after, Phase phase) {
|
||||
Proof phase(Phase value) { return new Proof(operation, delta, before, after, value); }
|
||||
}
|
||||
private final Path directory;
|
||||
AdminCoinOperationStore(Path data) { directory = data.resolve("admin-coin-operations"); }
|
||||
Optional<Proof> find(UUID operation) throws IOException {
|
||||
var path = directory.resolve(operation + ".proof");
|
||||
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Unsafe coin operation proof");
|
||||
var fields = new Properties();
|
||||
try (var input = Files.newInputStream(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var bytes = input.readNBytes(3_145_729);
|
||||
if (bytes.length > 3_145_728) throw new IOException("Coin operation proof too large");
|
||||
fields.load(new ByteArrayInputStream(bytes));
|
||||
}
|
||||
try {
|
||||
if (!fields.getProperty("schema").equals("1")) throw new IllegalArgumentException();
|
||||
var proof = new Proof(UUID.fromString(fields.getProperty("operation")), new BigInteger(fields.getProperty("delta")),
|
||||
CharacterYaml.decode(fields.getProperty("before")), CharacterYaml.decode(fields.getProperty("after")),
|
||||
Phase.valueOf(fields.getProperty("phase")));
|
||||
var before = proof.before();
|
||||
var receipts = new java.util.HashSet<>(before.rewardReceipts());
|
||||
if (receipts.size() < 4096) receipts.add(operation);
|
||||
var expected = new CharacterRecord(before.id(), before.name(), before.revision().add(BigInteger.ONE), before.stats(),
|
||||
before.level(), before.experience(), before.unspentPoints(), before.health(), before.learned(), before.loadout(),
|
||||
before.passives(), before.cooldowns(), before.restrictedKills(), before.dead(), before.deathId(), before.diedAt(),
|
||||
before.coins().add(proof.delta()), before.coinsInitialized(), receipts, before.pvpCoinEscrow(), before.gear(), before.sheetGeneration());
|
||||
if (!operation.equals(proof.operation()) || proof.delta().signum() == 0 || before.dead()
|
||||
|| !before.coinsInitialized() || before.rewardReceipts().contains(operation)
|
||||
|| !expected.equals(proof.after())) throw new IllegalArgumentException();
|
||||
return Optional.of(proof);
|
||||
} catch (RuntimeException invalid) { throw new IOException("Invalid coin operation proof"); }
|
||||
}
|
||||
void write(Proof proof) throws IOException {
|
||||
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS) && !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS))
|
||||
throw new IOException("Unsafe coin operation directory");
|
||||
Files.createDirectories(directory);
|
||||
var fields = new Properties();
|
||||
fields.setProperty("schema", "1"); fields.setProperty("operation", proof.operation().toString());
|
||||
fields.setProperty("delta", proof.delta().toString()); fields.setProperty("phase", proof.phase().name());
|
||||
fields.setProperty("before", CharacterYaml.encode(proof.before())); fields.setProperty("after", CharacterYaml.encode(proof.after()));
|
||||
var bytes = new ByteArrayOutputStream(); fields.store(bytes, "frozen administrator coin operation");
|
||||
var temporary = Files.createTempFile(directory, ".coins-", ".tmp");
|
||||
try {
|
||||
try (var output = FileChannel.open(temporary, StandardOpenOption.WRITE)) {
|
||||
var buffer = ByteBuffer.wrap(bytes.toByteArray());
|
||||
while (buffer.hasRemaining()) output.write(buffer);
|
||||
output.force(true);
|
||||
}
|
||||
Files.move(temporary, directory.resolve(proof.operation() + ".proof"), StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
DurableFiles.forceDirectory(directory);
|
||||
} finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,94 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
}
|
||||
|
||||
/** Pure authoritative read for administration; unlike gameplay loading, this never performs legacy migration. */
|
||||
public enum CoinAdjustmentStatus { APPLIED, DUPLICATE, STALE, UNAVAILABLE, BELOW_ZERO, FAILED, UNCERTAIN }
|
||||
public record CoinAdjustment(CoinAdjustmentStatus status, Optional<CharacterRecord> before,
|
||||
Optional<CharacterRecord> record) { }
|
||||
|
||||
/** Administrator arithmetic, not a combat reward; uses the same serialized write authority. */
|
||||
public CompletableFuture<CoinAdjustment> adjustCoins(UUID id, BigInteger revision, UUID operation, BigInteger delta) {
|
||||
return adjustCoins(id, revision, operation, delta, () -> true);
|
||||
}
|
||||
|
||||
/** Acceptance guard reads only process authority, never native player state on the disk worker. */
|
||||
public CompletableFuture<CoinAdjustment> adjustCoins(UUID id, BigInteger revision, UUID operation, BigInteger delta,
|
||||
java.util.function.BooleanSupplier eligible) {
|
||||
Objects.requireNonNull(id); Objects.requireNonNull(revision); Objects.requireNonNull(operation); Objects.requireNonNull(eligible);
|
||||
if (Objects.requireNonNull(delta).signum() == 0) throw new IllegalArgumentException("Nonzero delta required");
|
||||
return submit(() -> {
|
||||
var replacementStarted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
try { return repository.transaction(() -> {
|
||||
var proofs = new AdminCoinOperationStore(repository.pluginDataDirectory());
|
||||
var existing = proofs.find(operation);
|
||||
if (existing.isPresent()) {
|
||||
var proof = existing.orElseThrow();
|
||||
if (!proof.before().id().equals(id) || !proof.delta().equals(delta))
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.UNAVAILABLE, Optional.empty(), Optional.empty());
|
||||
if (proof.phase() == AdminCoinOperationStore.Phase.APPLIED) {
|
||||
var current = repository.load(id).orElse(null);
|
||||
if (current == null || current.revision().compareTo(proof.after().revision()) < 0
|
||||
|| current.revision().equals(proof.after().revision()) && !current.equals(proof.after()))
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.FAILED, Optional.empty(), Optional.empty());
|
||||
}
|
||||
var status = switch (proof.phase()) {
|
||||
case APPLIED -> CoinAdjustmentStatus.DUPLICATE;
|
||||
case FAILED -> CoinAdjustmentStatus.FAILED;
|
||||
case PREPARED, UNCERTAIN -> CoinAdjustmentStatus.UNCERTAIN;
|
||||
};
|
||||
return new CoinAdjustment(status, Optional.of(proof.before()), Optional.of(proof.after()));
|
||||
}
|
||||
var found = repository.load(id);
|
||||
if (found.isEmpty() || found.orElseThrow().dead() || !found.orElseThrow().coinsInitialized()
|
||||
|| !repository.mutationAvailable(id) || !eligible.getAsBoolean())
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.UNAVAILABLE, found, found);
|
||||
var old = found.orElseThrow();
|
||||
// A receipt without a frozen proof cannot authorize replay or fabricate an acknowledgment.
|
||||
if (old.rewardReceipts().contains(operation))
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.UNAVAILABLE, found, found);
|
||||
if (!old.revision().equals(revision)) return new CoinAdjustment(CoinAdjustmentStatus.STALE, found, found);
|
||||
if (old.coins().add(delta).signum() < 0) return new CoinAdjustment(CoinAdjustmentStatus.BELOW_ZERO, found, found);
|
||||
var receipts = new HashSet<>(old.rewardReceipts());
|
||||
// The permanent proof is authoritative; never evict someone else's receipt or freeze gameplay at ledger capacity.
|
||||
if (receipts.size() < 4096) receipts.add(operation);
|
||||
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
||||
old.level(), old.experience(), old.unspentPoints(), old.health(), old.learned(), old.loadout(),
|
||||
old.passives(), old.cooldowns(), old.restrictedKills(), old.dead(), old.deathId(), old.diedAt(),
|
||||
old.coins().add(delta), old.coinsInitialized(), receipts, old.pvpCoinEscrow(), old.gear(), old.sheetGeneration());
|
||||
var proof = new AdminCoinOperationStore.Proof(operation, delta, old, saved, AdminCoinOperationStore.Phase.PREPARED);
|
||||
try { proofs.write(proof); }
|
||||
catch (IOException precommit) { return new CoinAdjustment(CoinAdjustmentStatus.FAILED, found, found); }
|
||||
try {
|
||||
// Repeat custody/session authority after durable preparation, immediately before replacement.
|
||||
if (!repository.mutationAvailable(id) || !eligible.getAsBoolean()) {
|
||||
proofs.write(proof.phase(AdminCoinOperationStore.Phase.FAILED));
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.UNAVAILABLE, found, found);
|
||||
}
|
||||
replacementStarted.set(true);
|
||||
repository.replaceLocked(saved, old.revision(), true);
|
||||
proofs.write(proof.phase(AdminCoinOperationStore.Phase.APPLIED));
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.APPLIED, found, Optional.of(saved));
|
||||
} catch (IOException failure) {
|
||||
boolean unchanged = false;
|
||||
try { unchanged = repository.load(id).filter(old::equals).isPresent(); }
|
||||
catch (IOException unreadable) { /* Cannot establish a definite noncommit. */ }
|
||||
var status = unchanged ? CoinAdjustmentStatus.FAILED : CoinAdjustmentStatus.UNCERTAIN;
|
||||
try { proofs.write(proof.phase(unchanged ? AdminCoinOperationStore.Phase.FAILED : AdminCoinOperationStore.Phase.UNCERTAIN)); }
|
||||
catch (IOException retainedPreparation) { /* PREPARED remains fail-closed, never replayable. */ }
|
||||
return new CoinAdjustment(status, found, unchanged ? found : Optional.empty());
|
||||
}
|
||||
}); } catch (IOException | RuntimeException failure) {
|
||||
// Lookup/proof/lock failure before replacement is a proved noncommit, never a speculative uncertain write.
|
||||
return new CoinAdjustment(replacementStarted.get() ? CoinAdjustmentStatus.UNCERTAIN : CoinAdjustmentStatus.FAILED,
|
||||
Optional.empty(), Optional.empty());
|
||||
}
|
||||
}).exceptionally(failure -> {
|
||||
var cause = failure instanceof CompletionException ? failure.getCause() : failure;
|
||||
if (cause instanceof RejectedExecutionException)
|
||||
return new CoinAdjustment(CoinAdjustmentStatus.FAILED, Optional.empty(), Optional.empty());
|
||||
throw new CompletionException(failure); // Unexpected accepted-work failure remains conservative for its owner.
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<CharacterRecord>> inspect(UUID id) {
|
||||
return submit(() -> repository.load(Objects.requireNonNull(id)));
|
||||
}
|
||||
|
||||
@@ -94,14 +94,26 @@ public final class YamlCharacterRepository {
|
||||
if (!character.revision().equals(expectedRevision.add(BigInteger.ONE))) {
|
||||
throw new IOException("Character update must advance exactly one revision");
|
||||
}
|
||||
withLock(() -> {
|
||||
if (unavailable.test(character.id())) throw new IOException("Character is in dungeon boss custody");
|
||||
if (enforceMutationAvailability && mutationUnavailable.test(character.id()))
|
||||
throw new IOException("Character has unresolved recovery custody");
|
||||
CharacterRecord current = load(character.id()).orElseThrow(() -> new IOException("Character not found"));
|
||||
if (!current.revision().equals(expectedRevision)) throw new IOException("Stale character revision");
|
||||
write(character);
|
||||
});
|
||||
withLock(() -> replaceLocked(character, expectedRevision, enforceMutationAvailability));
|
||||
}
|
||||
|
||||
boolean mutationAvailable(UUID id) { return !unavailable.test(id) && !mutationUnavailable.test(id); }
|
||||
|
||||
/** Caller owns the same directory lock used by every character writer. */
|
||||
void replaceLocked(CharacterRecord character, BigInteger expectedRevision, boolean enforceAvailability) throws IOException {
|
||||
if (unavailable.test(character.id()) || enforceAvailability && mutationUnavailable.test(character.id()))
|
||||
throw new IOException("Character custody is unresolved");
|
||||
CharacterRecord current = load(character.id()).orElseThrow(() -> new IOException("Character not found"));
|
||||
if (!current.revision().equals(expectedRevision)
|
||||
|| !character.revision().equals(expectedRevision.add(BigInteger.ONE))) throw new IOException("Stale character revision");
|
||||
write(character);
|
||||
}
|
||||
|
||||
@FunctionalInterface interface Transaction<T> { T run() throws IOException; }
|
||||
<T> T transaction(Transaction<T> operation) throws IOException {
|
||||
var result = new java.util.concurrent.atomic.AtomicReference<T>();
|
||||
withLock(() -> result.set(operation.run()));
|
||||
return result.get();
|
||||
}
|
||||
|
||||
/** Only the in-memory creator of a never-issued batch may request this cleanup. */
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import games.dmg.fantasystick.events.AdminActionEventBridge;
|
||||
import games.dmg.fantasystick.events.AdminCoinsEventBridge;
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Full-UUID request owner. Disk work is serialized; native permission/session/feedback stays on the tick. */
|
||||
public final class AdminCharacterCoins implements AutoCloseable {
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessions sessions;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private volatile boolean closed;
|
||||
private final Set<Completion> pending = ConcurrentHashMap.newKeySet();
|
||||
private AdminActionEventBridge audit;
|
||||
private AdminCoinsEventBridge events;
|
||||
public AdminCharacterCoins(CharacterStorage characters, EquipmentSessions sessions, Consumer<Runnable> nextTick) {
|
||||
this.characters = characters; this.sessions = sessions; this.nextTick = nextTick;
|
||||
}
|
||||
public void attachAdminAudit(AdminActionEventBridge bridge) { audit = bridge; }
|
||||
public void attachEvents(AdminCoinsEventBridge bridge) { events = bridge; }
|
||||
public void adjust(CommandSender sender, UUID target, BigInteger delta) {
|
||||
var action = audit == null ? null : audit.current();
|
||||
var intent = events == null ? new AdminCoinsEventBridge.Intent(UUID.randomUUID(), action == null ? null : action.id(),
|
||||
java.time.Instant.now(), sender instanceof Player ? "player" : "console", null)
|
||||
: events.capture(sender, action == null ? null : action.id());
|
||||
result(action, AdminActionEventBridge.Outcome.PENDING, "owner_pending", Map.of());
|
||||
var acceptedLookup = new AtomicBoolean();
|
||||
characters.inspect(target).whenComplete((found, failure) -> {
|
||||
if (closed) { result(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", Map.of()); return; }
|
||||
try { nextTick.accept(() -> {
|
||||
if (!acceptedLookup.compareAndSet(false, true)) return;
|
||||
if (!valid(sender)) {
|
||||
result(action, AdminActionEventBridge.Outcome.REFUSED, "permission_changed", Map.of()); return;
|
||||
}
|
||||
if (failure != null || found == null || found.isEmpty() || found.orElseThrow().dead()
|
||||
|| !sessions.acceptsCoinAdjustment(target)) {
|
||||
result(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", Map.of());
|
||||
feedback(sender, "Coin adjustment refused: saved character is unavailable. Nothing changed."); return;
|
||||
}
|
||||
var before = found.orElseThrow();
|
||||
var active = sessions.activeCharacter(target).orElse(null);
|
||||
var completion = new Completion(sender, action, intent, before, active, delta);
|
||||
pending.add(completion);
|
||||
characters.adjustCoins(target, before.revision(), intent.operation(), delta,
|
||||
() -> !closed && sessions.acceptsCoinAdjustment(target)).whenComplete(completion::saved);
|
||||
}); } catch (RuntimeException rejected) {
|
||||
result(action, AdminActionEventBridge.Outcome.REFUSED, "owner_refused", Map.of());
|
||||
}
|
||||
});
|
||||
}
|
||||
private boolean valid(CommandSender sender) {
|
||||
return !closed && sender.hasPermission("fantasystick.admin") && (!(sender instanceof Player player) || player.isOnline());
|
||||
}
|
||||
|
||||
/** The disk acknowledgment is owned even when shutdown cancels every queued native task. */
|
||||
private final class Completion {
|
||||
final CommandSender sender;
|
||||
final AdminActionEventBridge.Action action;
|
||||
final AdminCoinsEventBridge.Intent intent;
|
||||
final CharacterRecord captured;
|
||||
final EquipmentSessions.Active active;
|
||||
final BigInteger delta;
|
||||
final AtomicBoolean finished = new AtomicBoolean();
|
||||
CharacterStorage.CoinAdjustment outcome;
|
||||
Throwable failure;
|
||||
boolean ready;
|
||||
Completion(CommandSender sender, AdminActionEventBridge.Action action, AdminCoinsEventBridge.Intent intent,
|
||||
CharacterRecord captured, EquipmentSessions.Active active, BigInteger delta) {
|
||||
this.sender = sender; this.action = action; this.intent = intent; this.captured = captured;
|
||||
this.active = active; this.delta = delta;
|
||||
}
|
||||
synchronized void saved(CharacterStorage.CoinAdjustment saved, Throwable error) {
|
||||
if (ready) return;
|
||||
outcome = saved; failure = error; ready = true;
|
||||
if (closed) { finish(false); return; }
|
||||
try { nextTick.accept(() -> finish(true)); }
|
||||
catch (RuntimeException rejected) { finish(false); }
|
||||
}
|
||||
synchronized void finish(boolean nativeAllowed) {
|
||||
if (!ready || !finished.compareAndSet(false, true)) return;
|
||||
pending.remove(this);
|
||||
boolean nativeFeedback = nativeAllowed && !closed;
|
||||
if (failure != null || outcome == null || outcome.status() == CharacterStorage.CoinAdjustmentStatus.UNCERTAIN) {
|
||||
result(action, AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", Map.of());
|
||||
if (nativeFeedback) feedback(sender, "Coin adjustment outcome uncertain; do not blindly repeat the command.");
|
||||
return;
|
||||
}
|
||||
if (outcome.status() != CharacterStorage.CoinAdjustmentStatus.APPLIED) {
|
||||
result(action, outcome.status() == CharacterStorage.CoinAdjustmentStatus.FAILED
|
||||
? AdminActionEventBridge.Outcome.FAILED : AdminActionEventBridge.Outcome.REFUSED,
|
||||
outcome.status() == CharacterStorage.CoinAdjustmentStatus.STALE ? "stale" : "owner_refused", Map.of());
|
||||
if (nativeFeedback) {
|
||||
var old = outcome.before().orElse(captured);
|
||||
feedback(sender, outcome.status() == CharacterStorage.CoinAdjustmentStatus.BELOW_ZERO
|
||||
? "Balance " + old.coins() + "; adjustment " + delta + " would produce " + old.coins().add(delta) + ". Nothing changed."
|
||||
: "Coin adjustment refused: character changed or is unavailable. Nothing changed.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
var before = outcome.before().orElseThrow(); var after = outcome.record().orElseThrow();
|
||||
String sync = active == null ? "not_applicable" : "not_current";
|
||||
if (nativeFeedback && active != null) {
|
||||
try { if (sessions.acknowledgeProgress(active, before.revision(), after)) sync = "acknowledged"; }
|
||||
catch (RuntimeException nativeFailure) { sync = "uncertain"; diagnostic("session acknowledgment", nativeFailure); }
|
||||
}
|
||||
try {
|
||||
if (events != null) events.adjusted(intent, before, after, delta, active == null ? "inactive" : "active", sync);
|
||||
} catch (RuntimeException eventFailure) { diagnostic("domain audit submission", eventFailure); }
|
||||
result(action, AdminActionEventBridge.Outcome.COMPLETED, "acknowledged", Map.of("domain_operation_id", intent.operation(),
|
||||
"domain_event_id", AdminCoinsEventBridge.eventId(intent.operation()), "subject_id", after.id()));
|
||||
if (nativeFeedback) feedback(sender, "Adjusted " + after.name() + " (" + after.id() + "): balance " + before.coins()
|
||||
+ "; adjustment " + delta + "; resulting balance " + after.coins() + ".");
|
||||
}
|
||||
}
|
||||
private void result(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome outcome, String reason, Map<String,Object> facts) {
|
||||
try { if (audit != null) audit.result(action, outcome, reason, facts); }
|
||||
catch (RuntimeException failure) { diagnostic("admin audit submission", failure); }
|
||||
}
|
||||
private void feedback(CommandSender sender, String message) {
|
||||
try { if (valid(sender)) sender.sendMessage(message); }
|
||||
catch (RuntimeException failure) { diagnostic("administrator feedback", failure); }
|
||||
}
|
||||
private static void diagnostic(String phase, Throwable failure) {
|
||||
java.util.logging.Logger.getLogger(AdminCharacterCoins.class.getName()).log(java.util.logging.Level.WARNING,
|
||||
"Administrator coins " + phase + " failed; this cannot change or replay the saved operation", failure);
|
||||
}
|
||||
@Override public void close() {
|
||||
closed = true;
|
||||
for (var completion : pending) completion.finish(false);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,11 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private AdminRevival adminRevival;
|
||||
private games.dmg.fantasystick.events.AdminRevivalEventBridge adminRevivalEvents;
|
||||
private AdminExperienceGrant experienceGrant;
|
||||
private AdminCharacterCoins characterCoins;
|
||||
public void attachCharacterCoins(AdminCharacterCoins owner) {
|
||||
characterCoins = Objects.requireNonNull(owner);
|
||||
if (adminAudit != null) owner.attachAdminAudit(adminAudit);
|
||||
}
|
||||
private games.dmg.fantasystick.persistence.AdminReviveSettings adminReviveSettings;
|
||||
private games.dmg.fantasystick.persistence.SwitchDelaySettings switchDelaySettings;
|
||||
private games.dmg.fantasystick.events.SwitchConfigEventBridge switchConfigEvents;
|
||||
@@ -137,6 +142,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
if (characterRecovery != null) characterRecovery.attachAdminAudit(audit);
|
||||
if (characterIssuer != null) characterIssuer.attachAdminAudit(audit);
|
||||
if (experienceGrant != null) experienceGrant.attachAdminAudit(audit);
|
||||
if (characterCoins != null) characterCoins.attachAdminAudit(audit);
|
||||
}
|
||||
|
||||
public EquipmentAdminCommand(EquipmentSessionStore receipts, EquipmentSessions sessions, Server server,
|
||||
@@ -728,6 +734,23 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
}
|
||||
|
||||
private void characterCommand(CommandSender sender, String[] args) {
|
||||
if (args.length >= 2 && args[1].equals("coins")) {
|
||||
if (!(sender instanceof org.bukkit.entity.Player) && !(sender instanceof org.bukkit.command.ConsoleCommandSender)) {
|
||||
adminRefused(); sender.sendMessage("Coin adjustment refused: use an authorized player or console."); return;
|
||||
}
|
||||
UUID target; java.math.BigInteger delta;
|
||||
try {
|
||||
if (args.length != 4 || characterCoins == null || !args[3].matches("[+-]?[0-9]+"))
|
||||
throw new IllegalArgumentException("Invalid coin command");
|
||||
target = UUID.fromString(args[2]);
|
||||
if (!target.toString().equalsIgnoreCase(args[2])) throw new IllegalArgumentException("Full UUID required");
|
||||
delta = new java.math.BigInteger(args[3]);
|
||||
if (delta.signum() == 0) throw new IllegalArgumentException("Nonzero delta required");
|
||||
} catch (IllegalArgumentException invalid) {
|
||||
adminInvalid(); sender.sendMessage("Usage: /fstickadmin character coins <full-character-uuid> <nonzero-signed-amount>"); return;
|
||||
}
|
||||
characterCoins.adjust(sender, target, delta); return;
|
||||
}
|
||||
if (args.length >= 2 && args[1].equals("find")) {
|
||||
characterFind(sender, args);
|
||||
return;
|
||||
@@ -2731,12 +2754,14 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
if(dungeonCommands!=null&&args.length>1){var dungeon=dungeonCommands.complete(sender,args);if(!dungeon.isEmpty())return dungeon;if(args[0].equals("dungeon"))return List.of();}
|
||||
if (args.length == 1) return matching(sender instanceof org.bukkit.entity.Player
|
||||
? List.of("adventure", "adventure-site", "character", "config", "dungeon", "experience", "give", "inspect", "party-registrar", "quest-giver", "rare-shop", "recover", "revive", "shop", "training-dummy")
|
||||
: List.of("adventure-site", "config", "dungeon", "experience", "give", "inspect", "party-registrar", "quest-giver", "rare-shop", "recover", "shop", "training-dummy"), args[0]);
|
||||
: List.of("adventure-site", "character", "config", "dungeon", "experience", "give", "inspect", "party-registrar", "quest-giver", "rare-shop", "recover", "shop", "training-dummy"), args[0]);
|
||||
if (args.length == 2 && args[0].equals("character")) {
|
||||
var routes = new java.util.ArrayList<>(List.of("find"));
|
||||
var routes = new java.util.ArrayList<>(List.of("coins", "find"));
|
||||
if (sender instanceof org.bukkit.entity.Player) routes.addAll(List.of("recover", "show", "view"));
|
||||
return matching(routes, args[1]);
|
||||
}
|
||||
if (args.length >= 3 && args[0].equals("character") && args[1].equals("coins"))
|
||||
return args.length == 3 ? matching(savedCharacterSuggestions().keySet().stream().map(UUID::toString).sorted().toList(), args[2]) : List.of();
|
||||
if (args.length >= 3 && args[0].equals("character") && args[1].equals("find")) {
|
||||
String prefix = String.join(" ", java.util.Arrays.copyOfRange(args, 2, args.length));
|
||||
return matchingIgnoreCase(savedCharacterSuggestions().values(), prefix);
|
||||
@@ -2935,5 +2960,5 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
.distinct().sorted(java.util.Comparator.comparing((String value) -> value.toLowerCase(java.util.Locale.ROOT))
|
||||
.thenComparing(java.util.Comparator.naturalOrder())).toList();
|
||||
}
|
||||
@Override public void close() { closed = true; savedSearches.clear(); if (characterIssuer != null) characterIssuer.close(); if(adminRevival!=null)adminRevival.close(); if(characterRecovery!=null)characterRecovery.close(); if(experienceGrant!=null)experienceGrant.close(); }
|
||||
@Override public void close() { closed = true; savedSearches.clear(); if (characterIssuer != null) characterIssuer.close(); if(adminRevival!=null)adminRevival.close(); if(characterRecovery!=null)characterRecovery.close(); if(experienceGrant!=null)experienceGrant.close(); if(characterCoins!=null)characterCoins.close(); }
|
||||
}
|
||||
@@ -387,6 +387,19 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
.map(attempt -> new Active(attempt.owner, attempt.session, attempt.character)).findFirst();
|
||||
}
|
||||
|
||||
/** Process-authority eligibility: safe on the serialized write worker; no native inventory/player calls. */
|
||||
public synchronized boolean acceptsCoinAdjustment(UUID character) {
|
||||
if (closed || characterRecoveries.containsKey(character) || unavailableCharacter.test(character)
|
||||
|| downedDirectory != null && downedDirectory.all().stream().anyMatch(value -> value.character().equals(character)
|
||||
&& (value.phase() == DownedEpisode.Phase.PENDING || !value.published()))) return false;
|
||||
if (java.util.stream.Stream.of(pending.values(), transitioning.values()).flatMap(java.util.Collection::stream)
|
||||
.anyMatch(attempt -> character.equals(attempt.character))) return false;
|
||||
return owned.values().stream().filter(attempt -> character.equals(attempt.character))
|
||||
.allMatch(attempt -> active.get(attempt.owner) == attempt && attempt.acknowledged && !attempt.downing
|
||||
&& attempt.downed == null && !attempt.exitRequested && !attempt.defeated && !attempt.cleaning
|
||||
&& !attempt.receiptUncertain && !attempt.uncertainSave && !attempt.nativeUncertain);
|
||||
}
|
||||
|
||||
/** Current native holder for a still-authorized server-thread action. */
|
||||
public synchronized Optional<Player> currentPlayer(Active session) {
|
||||
var attempt = active.get(session.player());
|
||||
|
||||
Reference in new issue
Block a user