244 lines
13 KiB
Java
244 lines
13 KiB
Java
package games.dmg.fantasystick.session;
|
|
|
|
import games.dmg.fantasystick.events.AdminActionEventBridge;
|
|
import games.dmg.fantasystick.events.AdminExperienceEventBridge;
|
|
import games.dmg.fantasystick.persistence.CharacterRecord;
|
|
import games.dmg.fantasystick.persistence.CharacterStorage;
|
|
import games.dmg.fantasystick.progression.ProgressionRules;
|
|
import java.math.BigInteger;
|
|
import java.util.Objects;
|
|
import java.util.UUID;
|
|
import java.util.function.Consumer;
|
|
import java.util.function.Function;
|
|
import org.bukkit.Color;
|
|
import org.bukkit.Sound;
|
|
import org.bukkit.entity.Player;
|
|
import org.bukkit.command.CommandSender;
|
|
|
|
/** Acknowledged administrator XP mutation captured against one exact active character/session. */
|
|
public final class AdminExperienceGrant implements AutoCloseable {
|
|
public enum Status { APPLIED, AT_CAP, STALE, UNAVAILABLE, FAILED }
|
|
public record Result(Status status, String name, BigInteger requested, BigInteger applied,
|
|
int level, int levels) { }
|
|
public record Failure(UUID character, Throwable cause) { }
|
|
|
|
private final CharacterStorage characters;
|
|
private final ProgressionRules progression;
|
|
private final EquipmentSessions sessions;
|
|
private final Consumer<Runnable> nextTick;
|
|
private final Function<UUID, Player> players;
|
|
private final Consumer<Failure> failures;
|
|
private final games.dmg.fantasystick.presentation.ParticleDelivery particles;
|
|
private volatile boolean closed;
|
|
private AdminExperienceEventBridge events;
|
|
private AdminActionEventBridge adminAudit;
|
|
|
|
public void attachAdminAudit(AdminActionEventBridge audit) {
|
|
if (closed || adminAudit != null) throw new IllegalStateException("Experience grant audit already attached");
|
|
adminAudit = Objects.requireNonNull(audit);
|
|
}
|
|
private final java.util.concurrent.ConcurrentMap<UUID, Pending> pending = new java.util.concurrent.ConcurrentHashMap<>();
|
|
|
|
private static final class Pending {
|
|
final AdminExperienceEventBridge.Intent intent;
|
|
final AdminActionEventBridge.Action action;
|
|
final UUID targetPlayer;
|
|
final CharacterRecord captured;
|
|
final BigInteger amount;
|
|
CharacterStorage.ExperienceAward award;
|
|
boolean saveFailed;
|
|
boolean resolved;
|
|
boolean emitted;
|
|
Pending(AdminExperienceEventBridge.Intent intent, AdminActionEventBridge.Action action,
|
|
UUID targetPlayer, CharacterRecord captured, BigInteger amount) {
|
|
this.intent = intent; this.action = action; this.targetPlayer = targetPlayer;
|
|
this.captured = captured; this.amount = amount;
|
|
}
|
|
}
|
|
|
|
public AdminExperienceGrant(CharacterStorage characters, ProgressionRules progression, EquipmentSessions sessions,
|
|
Consumer<Runnable> nextTick, Function<UUID, Player> players, Consumer<Failure> failures) {
|
|
this(characters, progression, sessions, nextTick, players, failures,
|
|
games.dmg.fantasystick.presentation.ParticleDelivery.legacyBroadcast());
|
|
}
|
|
public AdminExperienceGrant(CharacterStorage characters, ProgressionRules progression, EquipmentSessions sessions,
|
|
Consumer<Runnable> nextTick, Function<UUID, Player> players, Consumer<Failure> failures,
|
|
games.dmg.fantasystick.presentation.ParticleDelivery particles) {
|
|
this.characters = Objects.requireNonNull(characters);
|
|
this.progression = Objects.requireNonNull(progression);
|
|
this.sessions = Objects.requireNonNull(sessions);
|
|
this.nextTick = Objects.requireNonNull(nextTick);
|
|
this.players = Objects.requireNonNull(players);
|
|
this.failures = Objects.requireNonNull(failures);
|
|
this.particles = Objects.requireNonNull(particles);
|
|
}
|
|
|
|
public void attachEvents(AdminExperienceEventBridge bridge) {
|
|
if (closed || events != null) throw new IllegalStateException("Experience grant events unavailable");
|
|
events = Objects.requireNonNull(bridge);
|
|
}
|
|
|
|
/** Returns false before persistence when the captured active identity is no longer authoritative. */
|
|
public boolean grant(EquipmentSessions.Active active, CharacterRecord captured, BigInteger amount,
|
|
Consumer<Result> completion) {
|
|
return grant(active, captured, amount, null, completion);
|
|
}
|
|
|
|
public boolean grant(EquipmentSessions.Active active, CharacterRecord captured, BigInteger amount,
|
|
CommandSender administrator, Consumer<Result> completion) {
|
|
Objects.requireNonNull(active); Objects.requireNonNull(captured);
|
|
Objects.requireNonNull(amount); Objects.requireNonNull(completion);
|
|
if (amount.signum() <= 0) throw new IllegalArgumentException("Experience grant must be positive");
|
|
var action = adminAudit == null ? null : adminAudit.current();
|
|
if (closed || !sessions.current(active)
|
|
|| sessions.currentRecord(active).filter(captured::equals).isEmpty()) {
|
|
audit(action, AdminActionEventBridge.Outcome.REFUSED, "stale", java.util.Map.of());
|
|
return false;
|
|
}
|
|
AdminExperienceEventBridge.Intent intent = null;
|
|
if (events != null && administrator != null) {
|
|
Player target = null;
|
|
try { target = players.apply(active.player()); }
|
|
catch (RuntimeException failure) { report(captured.id(), failure); }
|
|
try { intent = events.capture(administrator, active, captured, target); }
|
|
catch (RuntimeException failure) { report(captured.id(), failure); }
|
|
}
|
|
var operation = new Pending(intent, action, active.player(), captured, amount);
|
|
if (intent != null) pending.put(intent.operation(), operation);
|
|
audit(action, AdminActionEventBridge.Outcome.PENDING, "owner_pending", java.util.Map.of());
|
|
try {
|
|
characters.awardExperience(captured.id(), captured.revision(), amount, progression)
|
|
.whenComplete((award, failure) -> schedule(active, operation, completion, award, failure));
|
|
} catch (RuntimeException failure) {
|
|
report(captured.id(), failure);
|
|
// An exception from the storage port cannot prove whether its write was accepted.
|
|
audit(action, AdminActionEventBridge.Outcome.UNCERTAIN, "operation_uncertain", java.util.Map.of());
|
|
if (intent != null) pending.remove(intent.operation(), operation);
|
|
throw failure;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private void schedule(EquipmentSessions.Active active, Pending operation,
|
|
Consumer<Result> completion, CharacterStorage.ExperienceAward award, Throwable failure) {
|
|
if (failure != null) report(operation.captured.id(), failure);
|
|
synchronized (operation) {
|
|
operation.award = award;
|
|
operation.saveFailed = failure != null;
|
|
operation.resolved = true;
|
|
}
|
|
if (closed) { publish(operation, false); return; }
|
|
try {
|
|
nextTick.accept(() -> complete(active, operation, completion, award, failure));
|
|
} catch (RuntimeException rejected) {
|
|
report(operation.captured.id(), rejected);
|
|
publish(operation, false);
|
|
}
|
|
}
|
|
|
|
private void complete(EquipmentSessions.Active active, Pending operation,
|
|
Consumer<Result> completion, CharacterStorage.ExperienceAward award, Throwable failure) {
|
|
if (closed) { publish(operation, false); return; }
|
|
var captured = operation.captured;
|
|
var amount = operation.amount;
|
|
if (failure != null) {
|
|
publish(operation, false);
|
|
completion.accept(new Result(Status.FAILED, captured.name(), amount, BigInteger.ZERO,
|
|
captured.level(), 0));
|
|
return;
|
|
}
|
|
var saved = award.record().orElse(captured);
|
|
Status status = switch (award.status()) {
|
|
case APPLIED -> Status.APPLIED;
|
|
case AT_CAP, UNCHANGED -> Status.AT_CAP;
|
|
case STALE -> Status.STALE;
|
|
case UNAVAILABLE -> Status.UNAVAILABLE;
|
|
};
|
|
BigInteger applied = status == Status.APPLIED
|
|
? saved.experience().subtract(captured.experience()) : BigInteger.ZERO;
|
|
boolean feedbackDelivered = false;
|
|
if (status == Status.APPLIED && sessions.current(active)) {
|
|
boolean synchronizedSession = sessions.acknowledgeProgress(active, captured.revision(), saved);
|
|
if (!synchronizedSession && sessions.current(active)
|
|
&& sessions.currentRecord(active).filter(saved::equals).isEmpty()) {
|
|
report(captured.id(), new IllegalStateException(
|
|
"Saved administrator XP could not synchronize with its captured active session"));
|
|
}
|
|
if (synchronizedSession && sessions.current(active))
|
|
feedbackDelivered = feedback(active, saved, applied, award.levels());
|
|
}
|
|
publish(operation, feedbackDelivered);
|
|
completion.accept(new Result(status, captured.name(), amount, applied, saved.level(), award.levels()));
|
|
}
|
|
|
|
private void publish(Pending operation, boolean feedbackDelivered) {
|
|
synchronized (operation) {
|
|
if (operation.emitted) return;
|
|
var award = operation.award;
|
|
if (!operation.resolved) return; // A later worker completion will observe close and retain the intent.
|
|
operation.emitted = true;
|
|
if (award != null && award.status() == CharacterStorage.ExperienceAwardStatus.APPLIED
|
|
&& award.record().isPresent()) {
|
|
var saved = award.record().orElseThrow();
|
|
if (events != null) events.granted(operation.intent, operation.captured, saved,
|
|
operation.amount, award.levels(), feedbackDelivered);
|
|
var facts = new java.util.LinkedHashMap<String, Object>();
|
|
if (operation.intent != null) facts.put("domain_operation_id", operation.intent.operation());
|
|
facts.put("subject_id", saved.id());
|
|
facts.put("target_id", operation.targetPlayer);
|
|
facts.put("requested", operation.amount.toString());
|
|
facts.put("applied", saved.experience().subtract(operation.captured.experience()).toString());
|
|
audit(operation.action, AdminActionEventBridge.Outcome.COMPLETED, "acknowledged", facts);
|
|
} else if (award == null) {
|
|
audit(operation.action, operation.saveFailed ? AdminActionEventBridge.Outcome.FAILED
|
|
: AdminActionEventBridge.Outcome.UNCERTAIN,
|
|
operation.saveFailed ? "operation_failed" : "operation_uncertain", java.util.Map.of());
|
|
} else {
|
|
var outcome = switch (award.status()) {
|
|
case AT_CAP, UNCHANGED, STALE, UNAVAILABLE -> AdminActionEventBridge.Outcome.REFUSED;
|
|
case APPLIED -> AdminActionEventBridge.Outcome.UNCERTAIN;
|
|
};
|
|
audit(operation.action, outcome, outcome == AdminActionEventBridge.Outcome.UNCERTAIN
|
|
? "operation_uncertain" : award.status() == CharacterStorage.ExperienceAwardStatus.STALE
|
|
? "stale" : "owner_refused", java.util.Map.of());
|
|
}
|
|
}
|
|
if (operation.intent != null) pending.remove(operation.intent.operation(), operation);
|
|
}
|
|
|
|
private void audit(AdminActionEventBridge.Action action, AdminActionEventBridge.Outcome outcome,
|
|
String reason, java.util.Map<String, Object> facts) {
|
|
var bridge = adminAudit;
|
|
if (bridge != null) bridge.result(action, outcome, reason, facts);
|
|
}
|
|
|
|
private boolean feedback(EquipmentSessions.Active active, CharacterRecord saved, BigInteger applied, int levels) {
|
|
Player player;
|
|
try { player = players.apply(active.player()); }
|
|
catch (RuntimeException failure) { report(saved.id(), failure); return false; }
|
|
if (player == null || !player.isOnline() || !sessions.current(active)
|
|
|| sessions.currentRecord(active).filter(saved::equals).isEmpty()) return false;
|
|
try {
|
|
player.sendMessage("Received " + applied + " fantasy XP from an administrator.");
|
|
for (int gained = 1; gained <= levels; gained++) {
|
|
int level = saved.level() - levels + gained;
|
|
player.sendMessage("Level " + level + "! Gained 1 character point.");
|
|
particles.world(org.bukkit.Particle.DUST, player.getLocation().add(0, 1, 0), 12,
|
|
0.3, 0.4, 0.3, 0, new org.bukkit.Particle.DustOptions(Color.BLUE, 1));
|
|
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1, 1);
|
|
}
|
|
return true;
|
|
} catch (RuntimeException failure) { report(saved.id(), failure); return false; }
|
|
}
|
|
|
|
private void report(UUID character, Throwable failure) {
|
|
try { failures.accept(new Failure(character, failure)); }
|
|
catch (RuntimeException ignored) { /* Diagnostics do not replay a grant. */ }
|
|
}
|
|
|
|
@Override public void close() {
|
|
closed = true;
|
|
for (var operation : pending.values()) publish(operation, false);
|
|
}
|
|
}
|