891 lines
65 KiB
Java
891 lines
65 KiB
Java
package games.dmg.fantasystick.persistence;
|
|
|
|
import games.dmg.fantasystick.progression.ProgressionRules;
|
|
import games.dmg.fantasystick.progression.Stat;
|
|
import java.io.IOException;
|
|
import java.math.BigInteger;
|
|
import java.time.Clock;
|
|
import java.time.Duration;
|
|
import java.time.Instant;
|
|
import java.util.ArrayList;
|
|
import java.util.HashSet;
|
|
import java.util.List;
|
|
import java.util.Set;
|
|
import java.util.Objects;
|
|
import java.util.Optional;
|
|
import java.util.UUID;
|
|
import java.util.concurrent.CompletableFuture;
|
|
import java.util.concurrent.CompletionException;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.concurrent.RejectedExecutionException;
|
|
|
|
/** Asynchronous character persistence; this does not cast Revive or consume/deliver inventory items. */
|
|
public final class CharacterStorage implements AutoCloseable {
|
|
private final YamlCharacterRepository repository;
|
|
private final Clock clock;
|
|
private final java.util.function.Supplier<games.dmg.fantasystick.progression.CoinRules> coinRules;
|
|
private final java.util.random.RandomGenerator coinRandom;
|
|
private final CharacterRecoveryStore recoveries;
|
|
private games.dmg.fantasystick.events.CoinEventBridge coinEvents;
|
|
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
|
task -> new Thread(task, "fantasy-character-persistence"));
|
|
|
|
public CharacterStorage(YamlCharacterRepository repository, Clock clock) {
|
|
this(repository, clock, games.dmg.fantasystick.progression.CoinRules::defaults,
|
|
java.util.random.RandomGenerator.getDefault());
|
|
}
|
|
|
|
public CharacterStorage(YamlCharacterRepository repository, Clock clock,
|
|
java.util.function.Supplier<games.dmg.fantasystick.progression.CoinRules> coinRules,
|
|
java.util.random.RandomGenerator coinRandom) {
|
|
this.repository = Objects.requireNonNull(repository);
|
|
this.clock = Objects.requireNonNull(clock);
|
|
this.coinRules = Objects.requireNonNull(coinRules);
|
|
this.coinRandom = Objects.requireNonNull(coinRandom);
|
|
this.recoveries = new CharacterRecoveryStore(repository.pluginDataDirectory());
|
|
repository.attachMutationUnavailable(recoveries::blocks);
|
|
}
|
|
|
|
public void attachUnavailableCharacter(java.util.function.Predicate<UUID> predicate){repository.attachUnavailable(predicate);}
|
|
public void attachCoinEvents(games.dmg.fantasystick.events.CoinEventBridge value){if(worker.isShutdown()||coinEvents!=null)throw new IllegalStateException("Coin events already attached or storage closed");coinEvents=Objects.requireNonNull(value);}
|
|
|
|
public CompletableFuture<Void> create(CharacterRecord character) {
|
|
return submit(() -> {
|
|
repository.create(character);
|
|
return null;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Prepare already allocated fresh characters off-thread. The caller validates configured
|
|
* starting points and retains the returned handle through success, cancellation and disable.
|
|
* No inventory access occurs here; abandoning an observer is not abandoning the attempt.
|
|
*/
|
|
public CraftPreparation prepareCraft(List<CharacterRecord> records) {return prepareCraft(records,"craft");}
|
|
public CraftPreparation prepareCraft(List<CharacterRecord> records,String source) {
|
|
var snapshot = List.copyOf(records);
|
|
var ids = new HashSet<UUID>();
|
|
if (snapshot.isEmpty()) throw new IllegalArgumentException("Craft batch must not be empty");
|
|
for (var record : snapshot) {
|
|
if (!ids.add(record.id()) || record.revision().signum() != 0 || record.name().isBlank()
|
|
|| record.dead() || record.deathId() != null || record.level() != 1
|
|
|| record.experience().signum() != 0 || record.stats().values().stream().anyMatch(value -> value.signum() != 0)
|
|
|| record.health().compareTo(java.math.BigDecimal.TEN) != 0
|
|
|| !record.learned().isEmpty() || record.passives().stream().anyMatch(id -> !id.isEmpty())
|
|
|| !record.cooldowns().isEmpty() || !record.coinsInitialized() || !record.rewardReceipts().isEmpty() || !record.gear().equals(CharacterGear.none())
|
|
|| record.loadout().stream().anyMatch(ability -> !ability.isEmpty())) {
|
|
throw new IllegalArgumentException("Craft batch requires distinct new characters");
|
|
}
|
|
}
|
|
return new CraftPreparation(snapshot,Objects.requireNonNull(source),coinRules.get());
|
|
}
|
|
|
|
public final class CraftPreparation {
|
|
private final List<CharacterRecord> requested;
|
|
private final CompletableFuture<CraftBatch> completion;
|
|
private final String source;
|
|
private final games.dmg.fantasystick.progression.CoinRules configuredRules;
|
|
private volatile boolean abandoned;
|
|
private CompletableFuture<CraftCleanup> cleanup;
|
|
|
|
private CraftPreparation(List<CharacterRecord> records,String source,games.dmg.fantasystick.progression.CoinRules configuredRules) {
|
|
requested = records;this.source=source;this.configuredRules=Objects.requireNonNull(configuredRules);
|
|
completion = writeCraftBatch(records, this);
|
|
}
|
|
|
|
/** Observation only; cancelling/timing out this copy does not cancel the owned operation. */
|
|
public CompletableFuture<CraftBatch> ready() { return completion.copy(); }
|
|
|
|
/** Retain this handle through completion; invalidate the attempt, not an observation future. */
|
|
public synchronized CompletableFuture<CraftCleanup> abandon() {
|
|
abandoned = true;
|
|
if (cleanup == null) {
|
|
cleanup = completion.handle((batch, failure) -> {
|
|
if (batch != null) return batch.abandon();
|
|
var cause = failure instanceof CompletionException ? failure.getCause() : failure;
|
|
var outcome = cause instanceof CraftPreparationException preparation ? preparation.cleanup()
|
|
: retainAll(requested);
|
|
return CompletableFuture.completedFuture(outcome);
|
|
}).thenCompose(result -> result);
|
|
}
|
|
return cleanup.copy();
|
|
}
|
|
}
|
|
|
|
private CompletableFuture<CraftBatch> writeCraftBatch(List<CharacterRecord> snapshot, CraftPreparation owner) {
|
|
return submit(() -> {
|
|
var created = new ArrayList<YamlCharacterRepository.Creation>();
|
|
UUID attempted = null;
|
|
try {
|
|
for (var record : snapshot) {
|
|
if (owner.abandoned) break;
|
|
attempted = record.id();
|
|
created.add(repository.createTracked(record));
|
|
attempted = null;
|
|
}
|
|
return new CraftBatch(created, owner);
|
|
} catch (IOException | RuntimeException failure) {
|
|
var cleanup = discardUnissued(created);
|
|
var retained = new HashSet<>(cleanup.retained());
|
|
if (attempted != null) retained.add(attempted);
|
|
throw new CraftPreparationException(failure, new CraftCleanup(cleanup.removed(), retained));
|
|
}
|
|
});
|
|
}
|
|
|
|
public static final class CraftPreparationException extends IOException {
|
|
@java.io.Serial private static final long serialVersionUID = 1L;
|
|
private final transient CraftCleanup cleanup;
|
|
|
|
private CraftPreparationException(Throwable cause, CraftCleanup cleanup) {
|
|
super("Character craft preparation failed; no batch was issued", cause);
|
|
this.cleanup = cleanup;
|
|
}
|
|
|
|
public CraftCleanup cleanup() { return cleanup; }
|
|
}
|
|
|
|
/** Removed includes already-absent files; retained includes failed writes whose outcome is unknown. */
|
|
public record CraftCleanup(Set<UUID> removed, Set<UUID> retained) {
|
|
public CraftCleanup {
|
|
removed = Set.copyOf(removed);
|
|
retained = Set.copyOf(retained);
|
|
}
|
|
}
|
|
|
|
public final class CraftBatch {
|
|
private final List<CharacterRecord> records;
|
|
private final List<YamlCharacterRepository.Creation> created;
|
|
private final CraftPreparation owner;
|
|
private boolean resolved;
|
|
private CompletableFuture<CraftCleanup> cleanup;
|
|
|
|
private CraftBatch(List<YamlCharacterRepository.Creation> created, CraftPreparation owner) {
|
|
this.owner = owner;
|
|
this.created = List.copyOf(created);
|
|
this.records = created.stream().map(creation -> creation.record).toList();
|
|
}
|
|
|
|
/** Reject a wrong-sized batch before giving up its never-issued cleanup proof. */
|
|
public synchronized Optional<List<CharacterRecord>> claimForDelivery(int expectedQuantity) {
|
|
if (expectedQuantity < 1 || records.size() != expectedQuantity) return Optional.empty();
|
|
return claimForDelivery();
|
|
}
|
|
|
|
/** One-use handoff immediately before native delivery; an exception afterward cannot authorize deletion. */
|
|
public synchronized Optional<List<CharacterRecord>> claimForDelivery() {
|
|
if (resolved || owner.abandoned) return Optional.empty();
|
|
resolved = true;
|
|
if (worker.isShutdown()) return Optional.empty();
|
|
var bridge=coinEvents;if(bridge!=null)for(var record:records)bridge.initialized(record,owner.source,owner.configuredRules);
|
|
return Optional.of(records);
|
|
}
|
|
|
|
public synchronized CompletableFuture<CraftCleanup> abandon() {
|
|
if (cleanup == null) {
|
|
if (resolved) {
|
|
cleanup = CompletableFuture.completedFuture(retainAll(records));
|
|
} else {
|
|
resolved = true;
|
|
cleanup = submit(() -> discardUnissued(created)).exceptionally(failure -> retainAll(records));
|
|
}
|
|
}
|
|
return cleanup.copy();
|
|
}
|
|
}
|
|
|
|
private static CraftCleanup retainAll(List<CharacterRecord> records) {
|
|
return new CraftCleanup(Set.of(), records.stream().map(CharacterRecord::id)
|
|
.collect(java.util.stream.Collectors.toSet()));
|
|
}
|
|
|
|
private CraftCleanup discardUnissued(List<YamlCharacterRepository.Creation> created) {
|
|
var removed = new HashSet<UUID>();
|
|
var retained = new HashSet<UUID>();
|
|
for (var creation : created) {
|
|
try {
|
|
if (repository.discardUnissued(creation)) removed.add(creation.record.id());
|
|
else retained.add(creation.record.id());
|
|
} catch (IOException exception) {
|
|
retained.add(creation.record.id());
|
|
}
|
|
}
|
|
return new CraftCleanup(removed, retained);
|
|
}
|
|
|
|
public record Catalog(List<CharacterRecord> records, int unreadable) {
|
|
public Catalog { records = List.copyOf(records); }
|
|
public boolean complete() { return unreadable == 0; }
|
|
}
|
|
|
|
public CompletableFuture<Catalog> catalog() {
|
|
return submit(() -> {
|
|
var catalog = repository.catalog();
|
|
return new Catalog(catalog.records(), catalog.unreadable());
|
|
});
|
|
}
|
|
|
|
/** Pure authoritative read for administration; unlike gameplay loading, this never performs legacy migration. */
|
|
public CompletableFuture<Optional<CharacterRecord>> inspect(UUID id) {
|
|
return submit(() -> repository.load(Objects.requireNonNull(id)));
|
|
}
|
|
|
|
public CompletableFuture<Optional<CharacterRecord>> find(UUID id) {
|
|
return submit(() -> load(id));
|
|
}
|
|
|
|
public enum RecoveryStatus { APPLIED, UNAVAILABLE, STALE, BLOCKED }
|
|
public record RecoveryRequest(UUID operation, UUID character, UUID administrator, UUID recipient,
|
|
BigInteger expectedRevision, BigInteger expectedGeneration,
|
|
boolean revive, UUID death, java.math.BigDecimal nativeLimit) {
|
|
public RecoveryRequest {
|
|
Objects.requireNonNull(operation); Objects.requireNonNull(character);
|
|
Objects.requireNonNull(administrator); Objects.requireNonNull(recipient);
|
|
Objects.requireNonNull(expectedRevision); Objects.requireNonNull(expectedGeneration);
|
|
Objects.requireNonNull(nativeLimit);
|
|
if (expectedRevision.signum() < 0 || expectedGeneration.signum() < 0
|
|
|| nativeLimit.signum() <= 0 || revive != (death != null))
|
|
throw new IllegalArgumentException("Invalid character recovery request");
|
|
}
|
|
}
|
|
public record RecoveryCommit(RecoveryStatus status, Optional<CharacterRecord> record, UUID operation) { }
|
|
|
|
/** Durable generation/revival commit; native delivery happens only after APPLIED acknowledgment. */
|
|
public CompletableFuture<RecoveryCommit> beginRecovery(RecoveryRequest request) {
|
|
Objects.requireNonNull(request);
|
|
return submit(() -> {
|
|
var found = repository.load(request.character());
|
|
if (found.isEmpty()) return new RecoveryCommit(RecoveryStatus.UNAVAILABLE, Optional.empty(), request.operation());
|
|
var old = found.orElseThrow();
|
|
reconcileRecovery(old);
|
|
if (!old.revision().equals(request.expectedRevision())
|
|
|| !old.sheetGeneration().equals(request.expectedGeneration()))
|
|
return new RecoveryCommit(RecoveryStatus.STALE, Optional.of(old), request.operation());
|
|
if (request.revive()) {
|
|
if (!old.dead() || !Objects.equals(old.deathId(), request.death()))
|
|
return new RecoveryCommit(RecoveryStatus.STALE, Optional.of(old), request.operation());
|
|
} else if (old.dead()) return new RecoveryCommit(RecoveryStatus.STALE, Optional.of(old), request.operation());
|
|
var existing = recoveries.find(old.id());
|
|
if (existing.isPresent() && existing.orElseThrow().phase() != CharacterRecoveryStore.Phase.DELIVERED)
|
|
return new RecoveryCommit(RecoveryStatus.BLOCKED, Optional.of(old), request.operation());
|
|
BigInteger nextGeneration = old.sheetGeneration().add(BigInteger.ONE);
|
|
var operation = new CharacterRecoveryStore.Operation(request.operation(), old.id(),
|
|
request.administrator(), request.recipient(), old.revision(), old.sheetGeneration(),
|
|
nextGeneration, request.revive(), request.death(), CharacterRecoveryStore.Phase.PREPARED);
|
|
recoveries.prepare(operation);
|
|
var health = request.revive() ? old.maximumHealth().min(request.nativeLimit()) : old.health();
|
|
var replacement = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
|
old.level(), old.experience(), old.unspentPoints(), health, old.learned(), old.loadout(), old.passives(),
|
|
old.cooldowns(), old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(),
|
|
old.coinsInitialized(), old.rewardReceipts(), request.revive() ? BigInteger.ZERO : old.pvpCoinEscrow(),
|
|
old.gear(), nextGeneration);
|
|
try { repository.replaceForRecovery(replacement, old.revision()); }
|
|
catch (IOException failure) {
|
|
try { recoveries.cancelPrepared(old.id(), request.operation()); }
|
|
catch (IOException retained) { failure.addSuppressed(retained); }
|
|
throw failure;
|
|
}
|
|
recoveries.advance(old.id(), request.operation(), CharacterRecoveryStore.Phase.PREPARED,
|
|
CharacterRecoveryStore.Phase.COMMITTED);
|
|
return new RecoveryCommit(RecoveryStatus.APPLIED, Optional.of(replacement), request.operation());
|
|
});
|
|
}
|
|
|
|
public CompletableFuture<Boolean> completeRecovery(UUID character, UUID operation) {
|
|
Objects.requireNonNull(character); Objects.requireNonNull(operation);
|
|
return submit(() -> {
|
|
var record = repository.load(character).orElseThrow(() -> new IOException("Recovered character missing"));
|
|
var proof = recoveries.find(character).orElseThrow(() -> new IOException("Recovery operation missing"));
|
|
if (!proof.operation().equals(operation) || proof.phase() != CharacterRecoveryStore.Phase.COMMITTED
|
|
|| !replacementMatches(record, proof))
|
|
throw new IOException("Recovery completion proof conflicts with saved character");
|
|
recoveries.advance(character, operation, CharacterRecoveryStore.Phase.COMMITTED,
|
|
CharacterRecoveryStore.Phase.DELIVERED);
|
|
return true;
|
|
});
|
|
}
|
|
|
|
/** Persist a legacy character's one-time configured migration roll before exposing it. */
|
|
private Optional<CharacterRecord> load(UUID id) throws IOException {
|
|
var found = repository.load(id);
|
|
if (found.isEmpty()) {
|
|
if (recoveries.find(id).filter(operation -> operation.phase() != CharacterRecoveryStore.Phase.DELIVERED).isPresent())
|
|
throw new IOException("Recovery proof references a missing character");
|
|
return found;
|
|
}
|
|
reconcileRecovery(found.orElseThrow());
|
|
if (found.orElseThrow().coinsInitialized()) return found;
|
|
var old = found.orElseThrow();
|
|
var configuredRules=coinRules.get();var migrated = 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(),
|
|
configuredRules.starting(coinRandom), true, old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(migrated, old.revision());var bridge=coinEvents;if(bridge!=null)bridge.initialized(migrated,"legacy_migration",configuredRules);
|
|
return Optional.of(migrated);
|
|
}
|
|
|
|
private void reconcileRecovery(CharacterRecord record) throws IOException {
|
|
var found = recoveries.find(record.id());
|
|
if (found.isEmpty()) return;
|
|
var operation = found.orElseThrow();
|
|
if (operation.phase() == CharacterRecoveryStore.Phase.PREPARED) {
|
|
if (expectedMatches(record, operation)) {
|
|
recoveries.cancelPrepared(record.id(), operation.operation());
|
|
return;
|
|
}
|
|
if (replacementMatches(record, operation)) {
|
|
recoveries.advance(record.id(), operation.operation(), CharacterRecoveryStore.Phase.PREPARED,
|
|
CharacterRecoveryStore.Phase.COMMITTED);
|
|
throw new IOException("Recovery committed before acknowledgment; custody is unresolved");
|
|
}
|
|
throw new IOException("Prepared recovery proof conflicts with saved character");
|
|
}
|
|
if (operation.phase() == CharacterRecoveryStore.Phase.COMMITTED) {
|
|
if (!replacementMatches(record, operation))
|
|
throw new IOException("Committed recovery proof conflicts with saved character");
|
|
throw new IOException("Character has unresolved committed recovery custody");
|
|
}
|
|
if (!record.sheetGeneration().equals(operation.replacementGeneration())
|
|
|| record.revision().compareTo(operation.expectedRevision().add(BigInteger.ONE)) < 0)
|
|
throw new IOException("Delivered recovery proof conflicts with saved character");
|
|
}
|
|
|
|
private static boolean expectedMatches(CharacterRecord record, CharacterRecoveryStore.Operation operation) {
|
|
return record.revision().equals(operation.expectedRevision())
|
|
&& record.sheetGeneration().equals(operation.expectedGeneration())
|
|
&& (operation.revive() ? record.dead() && Objects.equals(record.deathId(), operation.death()) : !record.dead());
|
|
}
|
|
|
|
private static boolean replacementMatches(CharacterRecord record, CharacterRecoveryStore.Operation operation) {
|
|
return record.revision().equals(operation.expectedRevision().add(BigInteger.ONE))
|
|
&& record.sheetGeneration().equals(operation.replacementGeneration())
|
|
&& !record.dead() && (!operation.revive() || Objects.equals(record.deathId(), operation.death()));
|
|
}
|
|
|
|
/** Persist an accepted native rename against the latest live record; never create a character from item metadata. */
|
|
public CompletableFuture<Optional<CharacterRecord>> renameCharacter(UUID characterId, String name) {
|
|
return renameCharacter(characterId, name, null);
|
|
}
|
|
|
|
public CompletableFuture<Optional<CharacterRecord>> renameCharacter(
|
|
UUID characterId, String name, BigInteger expectedSheetGeneration) {
|
|
Objects.requireNonNull(characterId);
|
|
Objects.requireNonNull(name);
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return Optional.empty();
|
|
var old = found.orElseThrow();
|
|
if (expectedSheetGeneration != null && !old.sheetGeneration().equals(expectedSheetGeneration))
|
|
return Optional.empty();
|
|
if (old.name().equals(name)) return Optional.of(old);
|
|
var renamed = new CharacterRecord(old.id(), 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(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(renamed, old.revision());
|
|
return Optional.of(renamed);
|
|
});
|
|
}
|
|
|
|
public enum ExperienceAwardStatus { APPLIED, AT_CAP, UNCHANGED, STALE, UNAVAILABLE }
|
|
public record ExperienceAward(ExperienceAwardStatus status, Optional<CharacterRecord> record, int levels) { }
|
|
|
|
/** Persist configured transferable XP/level/point progression as one expected revision. */
|
|
public CompletableFuture<ExperienceAward> awardExperience(UUID characterId, BigInteger expectedRevision,
|
|
BigInteger reward, ProgressionRules rules) {
|
|
Objects.requireNonNull(characterId);
|
|
Objects.requireNonNull(expectedRevision);
|
|
Objects.requireNonNull(reward);
|
|
Objects.requireNonNull(rules);
|
|
if (reward.signum() < 0) throw new IllegalArgumentException("Experience reward must not be negative");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new ExperienceAward(ExperienceAwardStatus.UNAVAILABLE, Optional.empty(), 0);
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) {
|
|
return new ExperienceAward(ExperienceAwardStatus.STALE, Optional.of(old), 0);
|
|
}
|
|
var cap = rules.xpPerLevel().multiply(BigInteger.valueOf(rules.maximumLevel() - 1L));
|
|
if (old.level() >= rules.maximumLevel() || old.experience().compareTo(cap) >= 0) {
|
|
return new ExperienceAward(ExperienceAwardStatus.AT_CAP, Optional.of(old), 0);
|
|
}
|
|
var experience = old.experience().add(reward).min(cap);
|
|
if (experience.equals(old.experience())) {
|
|
var status = old.level() >= rules.maximumLevel()
|
|
? ExperienceAwardStatus.AT_CAP : ExperienceAwardStatus.UNCHANGED;
|
|
return new ExperienceAward(status, Optional.of(old), 0);
|
|
}
|
|
int level = experience.divide(rules.xpPerLevel()).intValueExact() + 1;
|
|
int gained = Math.max(0, level - old.level());
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
|
level, experience, old.unspentPoints().add(BigInteger.valueOf(gained)), old.health(), old.learned(),
|
|
old.loadout(), old.passives(), old.cooldowns(), old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new ExperienceAward(ExperienceAwardStatus.APPLIED, Optional.of(saved), gained);
|
|
});
|
|
}
|
|
|
|
public enum CoinSpendStatus { APPLIED, DUPLICATE, INSUFFICIENT, STALE, UNAVAILABLE }
|
|
public record CoinSpend(CoinSpendStatus status, Optional<CharacterRecord> record) { }
|
|
|
|
/** Persist one operation-keyed debit; an acknowledged operation can never charge twice. */
|
|
public CompletableFuture<CoinSpend> spendCoins(UUID characterId, BigInteger expectedRevision, UUID operationId,
|
|
BigInteger amount) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision);
|
|
Objects.requireNonNull(operationId); Objects.requireNonNull(amount);
|
|
if (amount.signum() < 0) throw new IllegalArgumentException("Coin debit must not be negative");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new CoinSpend(CoinSpendStatus.UNAVAILABLE, Optional.empty());
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (old.rewardReceipts().contains(operationId)) {
|
|
return new CoinSpend(CoinSpendStatus.DUPLICATE, Optional.of(old));
|
|
}
|
|
if (!old.revision().equals(expectedRevision)) {
|
|
return new CoinSpend(CoinSpendStatus.STALE, Optional.of(old));
|
|
}
|
|
if (old.coins().compareTo(amount) < 0) {
|
|
return new CoinSpend(CoinSpendStatus.INSUFFICIENT, Optional.of(old));
|
|
}
|
|
var receipts = new java.util.HashSet<>(old.rewardReceipts());
|
|
if (receipts.size() >= 4096) receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());
|
|
receipts.add(operationId);
|
|
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(), false, old.deathId(), old.diedAt(),
|
|
old.coins().subtract(amount), true, receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new CoinSpend(CoinSpendStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
public enum CoinRefundStatus { APPLIED, DUPLICATE, UNAVAILABLE }
|
|
public record CoinRefund(CoinRefundStatus status,Optional<CharacterRecord> record){}
|
|
/** Compensate a persisted debit exactly once while retaining both audit receipts. */
|
|
public CompletableFuture<CoinRefund> refundCoins(UUID characterId,UUID debitId,UUID refundId,BigInteger amount){Objects.requireNonNull(characterId);Objects.requireNonNull(debitId);Objects.requireNonNull(refundId);Objects.requireNonNull(amount);if(amount.signum()<0)throw new IllegalArgumentException("Coin refund must not be negative");return submit(()->{var found=repository.load(characterId);if(found.isEmpty())return new CoinRefund(CoinRefundStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(refundId))return new CoinRefund(CoinRefundStatus.DUPLICATE,Optional.of(old));if(!old.rewardReceipts().contains(debitId))return new CoinRefund(CoinRefundStatus.UNAVAILABLE,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().filter(id->!id.equals(debitId)).min(UUID::compareTo).orElseThrow());receipts.add(refundId);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(amount),old.coinsInitialized(),receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new CoinRefund(CoinRefundStatus.APPLIED,Optional.of(saved));});}
|
|
|
|
public enum GearPurchaseStatus { APPLIED,DUPLICATE,INSUFFICIENT,NOT_UPGRADE,STALE,UNAVAILABLE }
|
|
public record GearPurchase(GearPurchaseStatus status,Optional<CharacterRecord> record){}
|
|
/** One character-file transaction owns both the exact coin debit and strict gear replacement. */
|
|
public CompletableFuture<GearPurchase> purchaseGear(UUID characterId,BigInteger expectedRevision,UUID operationId,GearSlot slot,GearTier target,BigInteger price){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(slot);Objects.requireNonNull(target);Objects.requireNonNull(price);if(target==GearTier.NONE||price.signum()<0)throw new IllegalArgumentException("Invalid gear purchase");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new GearPurchase(GearPurchaseStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new GearPurchase(GearPurchaseStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new GearPurchase(GearPurchaseStatus.STALE,Optional.of(old));if(!target.higherThan(old.gear().tier(slot)))return new GearPurchase(GearPurchaseStatus.NOT_UPGRADE,Optional.of(old));if(old.coins().compareTo(price)<0)return new GearPurchase(GearPurchaseStatus.INSUFFICIENT,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);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(),false,old.deathId(),old.diedAt(),old.coins().subtract(price),true,receipts,old.pvpCoinEscrow(),old.gear().with(slot,target),old.sheetGeneration());repository.replace(saved,old.revision());return new GearPurchase(GearPurchaseStatus.APPLIED,Optional.of(saved));});}
|
|
|
|
public enum RarePurchaseStatus { APPLIED,DUPLICATE,INSUFFICIENT,STALE,UNAVAILABLE }
|
|
public record RarePurchase(RarePurchaseStatus status,Optional<CharacterRecord> record){}
|
|
/** One character-file transaction owns a rare purchase's exact idempotent coin debit. */
|
|
public CompletableFuture<RarePurchase> purchaseRare(UUID characterId,BigInteger expectedRevision,UUID operationId,BigInteger price){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(price);if(price.signum()<=0)throw new IllegalArgumentException("Invalid rare purchase");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new RarePurchase(RarePurchaseStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new RarePurchase(RarePurchaseStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new RarePurchase(RarePurchaseStatus.STALE,Optional.of(old));if(old.coins().compareTo(price)<0)return new RarePurchase(RarePurchaseStatus.INSUFFICIENT,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);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(),false,old.deathId(),old.diedAt(),old.coins().subtract(price),true,receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new RarePurchase(RarePurchaseStatus.APPLIED,Optional.of(saved));});}
|
|
|
|
public enum MagicCoreStatus { APPLIED,DUPLICATE,STALE,UNAVAILABLE }
|
|
public record MagicCore(MagicCoreStatus status,Optional<CharacterRecord> record){}
|
|
/** Credit one ordinary arbitrary-precision point with stable consume proof. */
|
|
public CompletableFuture<MagicCore> consumeMagicCore(UUID characterId,BigInteger expectedRevision,UUID operationId){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new MagicCore(MagicCoreStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new MagicCore(MagicCoreStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new MagicCore(MagicCoreStatus.STALE,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints().add(BigInteger.ONE),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins(),old.coinsInitialized(),receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new MagicCore(MagicCoreStatus.APPLIED,Optional.of(saved));});}
|
|
|
|
public enum ReskillStatus { APPLIED,DUPLICATE,NOTHING_TO_RESET,STALE,UNAVAILABLE }
|
|
public record Reskill(ReskillStatus status,Optional<CharacterRecord> record){}
|
|
/** Reset every one-point character investment and preserve identity/progress/deadlines in one revision. */
|
|
public CompletableFuture<Reskill> reskill(UUID characterId,BigInteger expectedRevision,UUID operationId,java.math.BigDecimal nativeHealthLimit){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(nativeHealthLimit);if(nativeHealthLimit.signum()<=0)throw new IllegalArgumentException("Invalid native health limit");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new Reskill(ReskillStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new Reskill(ReskillStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new Reskill(ReskillStatus.STALE,Optional.of(old));BigInteger refund=old.stats().values().stream().reduce(BigInteger.ZERO,BigInteger::add).add(BigInteger.valueOf(old.learned().size())).add(BigInteger.valueOf(old.passives().stream().filter(id->!id.isEmpty()).distinct().count()));if(refund.signum()==0)return new Reskill(ReskillStatus.NOTHING_TO_RESET,Optional.of(old));var stats=new java.util.EnumMap<Stat,BigInteger>(Stat.class);for(var stat:Stat.values())stats.put(stat,BigInteger.ZERO);var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var health=old.health().min(java.math.BigDecimal.TEN.min(nativeHealthLimit));var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),stats,old.level(),old.experience(),old.unspentPoints().add(refund),health,Set.of(),List.of("","","","","","",""),List.of("","",""),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins(),old.coinsInitialized(),receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new Reskill(ReskillStatus.APPLIED,Optional.of(saved));});}
|
|
|
|
public enum CombatAwardStatus { APPLIED, SPACING_BLOCKED, AT_CAP, UNCHANGED, DUPLICATE, STALE, UNAVAILABLE }
|
|
public record CombatAward(CombatAwardStatus status, Optional<CharacterRecord> record, int levels) { }
|
|
|
|
/** Compatibility route for callers that do not yet carry a stable reward identity or coins. */
|
|
public CompletableFuture<CombatAward> awardCombatExperience(UUID characterId, BigInteger expectedRevision,
|
|
BigInteger reward, ProgressionRules progression,
|
|
games.dmg.fantasystick.progression.CombatRewardRules rewards,
|
|
games.dmg.fantasystick.progression.CombatRewardRules.KillPosition restrictedKill) {
|
|
return awardCombatReward(characterId, expectedRevision, UUID.randomUUID(), reward, BigInteger.ZERO,
|
|
progression, rewards, restrictedKill);
|
|
}
|
|
|
|
/** Persist one idempotent XP/coin recipient share, receipt and spacing reference in one revision. */
|
|
public CompletableFuture<CombatAward> awardCombatReward(UUID characterId, BigInteger expectedRevision, UUID rewardId,
|
|
BigInteger experienceReward, BigInteger coinReward, ProgressionRules progression,
|
|
games.dmg.fantasystick.progression.CombatRewardRules rewards,
|
|
games.dmg.fantasystick.progression.CombatRewardRules.KillPosition restrictedKill) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(rewardId);
|
|
Objects.requireNonNull(experienceReward); Objects.requireNonNull(coinReward);
|
|
Objects.requireNonNull(progression); Objects.requireNonNull(rewards);
|
|
if (experienceReward.signum() < 0 || coinReward.signum() < 0) {
|
|
throw new IllegalArgumentException("Combat rewards must not be negative");
|
|
}
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new CombatAward(CombatAwardStatus.UNAVAILABLE, Optional.empty(), 0);
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (old.rewardReceipts().contains(rewardId)) {
|
|
return new CombatAward(CombatAwardStatus.DUPLICATE, Optional.of(old), 0);
|
|
}
|
|
if (!old.revision().equals(expectedRevision)) {
|
|
return new CombatAward(CombatAwardStatus.STALE, Optional.of(old), 0);
|
|
}
|
|
boolean eligible = restrictedKill == null || old.restrictedKills().get(restrictedKill.world()) == null
|
|
|| rewards.spaced(old.restrictedKills().get(restrictedKill.world()), restrictedKill);
|
|
var history = new java.util.HashMap<>(old.restrictedKills());
|
|
if (restrictedKill != null) history.put(restrictedKill.world(), restrictedKill);
|
|
var cap = progression.xpPerLevel().multiply(BigInteger.valueOf(progression.maximumLevel() - 1L));
|
|
boolean atCap = old.level() >= progression.maximumLevel() || old.experience().compareTo(cap) >= 0;
|
|
var experience = eligible && !atCap ? old.experience().add(experienceReward).min(cap) : old.experience();
|
|
int level = atCap ? old.level() : experience.divide(progression.xpPerLevel()).intValueExact() + 1;
|
|
int gained = Math.max(0, level - old.level());
|
|
var status = !eligible ? CombatAwardStatus.SPACING_BLOCKED : atCap ? CombatAwardStatus.AT_CAP
|
|
: experience.equals(old.experience()) && coinReward.signum() == 0
|
|
? CombatAwardStatus.UNCHANGED : CombatAwardStatus.APPLIED;
|
|
var receipts = new java.util.HashSet<>(old.rewardReceipts());
|
|
if (receipts.size() >= 4096) receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());
|
|
receipts.add(rewardId);
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
|
level, experience, old.unspentPoints().add(BigInteger.valueOf(gained)), old.health(), old.learned(),
|
|
old.loadout(), old.passives(), old.cooldowns(), history, false, old.deathId(), old.diedAt(),
|
|
old.coins().add(eligible ? coinReward : BigInteger.ZERO), true, receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new CombatAward(status, Optional.of(saved), gained);
|
|
});
|
|
}
|
|
|
|
public enum PassiveMutationStatus {
|
|
APPLIED, STALE, REQUIREMENTS, NO_POINTS, PASSIVE_SLOTS_FULL, ALREADY_LEARNED,
|
|
NOT_LEARNED, REQUIRED_BY_LEARNED, UNAVAILABLE
|
|
}
|
|
public record PassiveMutation(PassiveMutationStatus status, Optional<CharacterRecord> record) { }
|
|
|
|
/** Learn one registered passive in the lowest empty independent slot as one character revision. */
|
|
public CompletableFuture<PassiveMutation> unlockPassive(UUID characterId, BigInteger expectedRevision, String passive,
|
|
java.util.Map<Stat, BigInteger> requirements, Set<String> prerequisites, BigInteger cost) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(passive);
|
|
Objects.requireNonNull(requirements); Objects.requireNonNull(prerequisites); Objects.requireNonNull(cost);
|
|
if (!passive.matches("[a-z][a-z0-9_]{0,63}") || !cost.equals(BigInteger.ONE)
|
|
|| requirements.entrySet().stream().anyMatch(entry -> entry.getValue().compareTo(BigInteger.TEN) < 0)
|
|
|| prerequisites.stream().anyMatch(String::isBlank)) {
|
|
throw new IllegalArgumentException("Invalid passive unlock");
|
|
}
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new PassiveMutation(PassiveMutationStatus.UNAVAILABLE, Optional.empty());
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new PassiveMutation(PassiveMutationStatus.STALE, Optional.of(old));
|
|
if (old.passives().contains(passive)) return new PassiveMutation(PassiveMutationStatus.ALREADY_LEARNED, Optional.of(old));
|
|
if (!old.passives().containsAll(prerequisites) || requirements.entrySet().stream()
|
|
.anyMatch(entry -> old.stats().get(entry.getKey()).compareTo(entry.getValue()) < 0)) {
|
|
return new PassiveMutation(PassiveMutationStatus.REQUIREMENTS, Optional.of(old));
|
|
}
|
|
if (old.unspentPoints().compareTo(cost) < 0) return new PassiveMutation(PassiveMutationStatus.NO_POINTS, Optional.of(old));
|
|
int slot = old.passives().indexOf("");
|
|
if (slot < 0) return new PassiveMutation(PassiveMutationStatus.PASSIVE_SLOTS_FULL, Optional.of(old));
|
|
var passives = new java.util.ArrayList<>(old.passives()); passives.set(slot, passive);
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
|
old.experience(), old.unspentPoints().subtract(cost), old.health(), old.learned(), old.loadout(), passives,
|
|
old.cooldowns(), old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new PassiveMutation(PassiveMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
/** Refund one passive once while refusing removal beneath a registered learned dependent. */
|
|
public CompletableFuture<PassiveMutation> unlearnPassive(UUID characterId, BigInteger expectedRevision,
|
|
String passive, Set<String> learnedDependents) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(passive);
|
|
Objects.requireNonNull(learnedDependents);
|
|
if (!passive.matches("[a-z][a-z0-9_]{0,63}") || learnedDependents.stream().anyMatch(String::isBlank)) {
|
|
throw new IllegalArgumentException("Invalid passive refund");
|
|
}
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new PassiveMutation(PassiveMutationStatus.UNAVAILABLE, Optional.empty());
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new PassiveMutation(PassiveMutationStatus.STALE, Optional.of(old));
|
|
if (!old.passives().contains(passive)) return new PassiveMutation(PassiveMutationStatus.NOT_LEARNED, Optional.of(old));
|
|
if (old.passives().stream().anyMatch(learnedDependents::contains)) {
|
|
return new PassiveMutation(PassiveMutationStatus.REQUIRED_BY_LEARNED, Optional.of(old));
|
|
}
|
|
var passives = old.passives().stream().map(id -> id.equals(passive) ? "" : id).toList();
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
|
old.experience(), old.unspentPoints().add(BigInteger.ONE), old.health(), old.learned(), old.loadout(), passives,
|
|
old.cooldowns(), old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new PassiveMutation(PassiveMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
public enum AbilityMutationStatus {
|
|
APPLIED, UNCHANGED, STALE, REQUIREMENTS, NO_POINTS, LOADOUT_FULL, ALREADY_LEARNED, NOT_LEARNED, COOLDOWN, UNAVAILABLE
|
|
}
|
|
public record AbilityMutation(AbilityMutationStatus status, Optional<CharacterRecord> record) { }
|
|
|
|
/** Unlock one validated registered ID and spend its points in the same expected revision. */
|
|
public CompletableFuture<AbilityMutation> unlockAbility(UUID characterId, BigInteger expectedRevision, String ability,
|
|
java.util.Map<Stat, BigInteger> requirements, BigInteger cost) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(ability);
|
|
Objects.requireNonNull(requirements); Objects.requireNonNull(cost);
|
|
if (ability.isBlank() || !cost.equals(BigInteger.ONE) || requirements.entrySet().stream().anyMatch(entry -> entry.getValue().compareTo(BigInteger.TEN) < 0)) {
|
|
throw new IllegalArgumentException("Invalid ability unlock");
|
|
}
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return new AbilityMutation(AbilityMutationStatus.UNAVAILABLE, Optional.empty());
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new AbilityMutation(AbilityMutationStatus.STALE, Optional.of(old));
|
|
if (old.learned().contains(ability)) return new AbilityMutation(AbilityMutationStatus.ALREADY_LEARNED, Optional.of(old));
|
|
if (requirements.entrySet().stream().anyMatch(entry -> old.stats().get(entry.getKey()).compareTo(entry.getValue()) < 0)) {
|
|
return new AbilityMutation(AbilityMutationStatus.REQUIREMENTS, Optional.of(old));
|
|
}
|
|
if (old.unspentPoints().compareTo(cost) < 0) return new AbilityMutation(AbilityMutationStatus.NO_POINTS, Optional.of(old));
|
|
int slot = old.loadout().indexOf("");
|
|
if (slot < 0) return new AbilityMutation(AbilityMutationStatus.LOADOUT_FULL, Optional.of(old));
|
|
var learned = new java.util.HashSet<>(old.learned()); learned.add(ability);
|
|
var loadout = new java.util.ArrayList<>(old.loadout()); loadout.set(slot, ability);
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
|
old.experience(), old.unspentPoints().subtract(cost), old.health(), learned, loadout, old.passives(), old.cooldowns(),
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new AbilityMutation(AbilityMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
/** Refund one learned ability exactly once, clear every equipped reference and retain its deadline. */
|
|
public CompletableFuture<AbilityMutation> unlearnAbility(UUID characterId, BigInteger expectedRevision, String ability) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(ability);
|
|
if (ability.isBlank()) throw new IllegalArgumentException("Invalid ability refund");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return new AbilityMutation(AbilityMutationStatus.UNAVAILABLE, Optional.empty());
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new AbilityMutation(AbilityMutationStatus.STALE, Optional.of(old));
|
|
if (!old.learned().contains(ability)) return new AbilityMutation(AbilityMutationStatus.NOT_LEARNED, Optional.of(old));
|
|
var learned = new java.util.HashSet<>(old.learned()); learned.remove(ability);
|
|
var loadout = old.loadout().stream().map(assigned -> assigned.equals(ability) ? "" : assigned).toList();
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
|
old.experience(), old.unspentPoints().add(BigInteger.ONE), old.health(), learned, loadout, old.passives(), old.cooldowns(),
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new AbilityMutation(AbilityMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
/** Move one learned ability to one of the seven selectable slots without duplicating it. */
|
|
public CompletableFuture<AbilityMutation> assignAbility(UUID characterId, BigInteger expectedRevision,
|
|
String ability, int slot) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(ability);
|
|
if (ability.isBlank() || slot < 0 || slot >= 7) throw new IllegalArgumentException("Invalid ability assignment");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return new AbilityMutation(AbilityMutationStatus.UNAVAILABLE, Optional.empty());
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new AbilityMutation(AbilityMutationStatus.STALE, Optional.of(old));
|
|
if (!old.learned().contains(ability)) return new AbilityMutation(AbilityMutationStatus.NOT_LEARNED, Optional.of(old));
|
|
var loadout = new java.util.ArrayList<>(old.loadout());
|
|
for (int index = 0; index < loadout.size(); index++) if (loadout.get(index).equals(ability)) loadout.set(index, "");
|
|
loadout.set(slot, ability);
|
|
if (loadout.equals(old.loadout())) return new AbilityMutation(AbilityMutationStatus.UNCHANGED, Optional.of(old));
|
|
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(), loadout, old.passives(), old.cooldowns(),
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new AbilityMutation(AbilityMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
/** Commit a real-time character/ability deadline before exposing the cast's native effect. */
|
|
public CompletableFuture<AbilityMutation> commitAbilityCooldown(UUID characterId, BigInteger expectedRevision,
|
|
String ability, Instant readyAt) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision); Objects.requireNonNull(ability);
|
|
Objects.requireNonNull(readyAt);
|
|
if (ability.isBlank()) throw new IllegalArgumentException("Invalid ability cooldown");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return new AbilityMutation(AbilityMutationStatus.UNAVAILABLE, Optional.empty());
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) return new AbilityMutation(AbilityMutationStatus.STALE, Optional.of(old));
|
|
if (!old.learned().contains(ability)) return new AbilityMutation(AbilityMutationStatus.NOT_LEARNED, Optional.of(old));
|
|
Instant previous = old.cooldowns().get(ability);
|
|
if (previous != null && previous.isAfter(clock.instant())) return new AbilityMutation(AbilityMutationStatus.COOLDOWN, Optional.of(old));
|
|
if (readyAt.equals(previous)) return new AbilityMutation(AbilityMutationStatus.UNCHANGED, Optional.of(old));
|
|
var cooldowns = new java.util.HashMap<>(old.cooldowns()); cooldowns.put(ability, readyAt);
|
|
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(), cooldowns,
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new AbilityMutation(AbilityMutationStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
public enum StatPurchaseStatus { APPLIED, STALE, NO_POINTS, UNAVAILABLE }
|
|
public record StatPurchase(StatPurchaseStatus status, Optional<CharacterRecord> record) { }
|
|
|
|
/** Persist one active-session stat purchase and its current native health as one revision. */
|
|
public CompletableFuture<StatPurchase> purchaseStat(UUID characterId, BigInteger expectedRevision, Stat stat,
|
|
java.math.BigDecimal currentHealth,
|
|
java.math.BigDecimal nativeLimit) {
|
|
Objects.requireNonNull(characterId);
|
|
Objects.requireNonNull(expectedRevision);
|
|
Objects.requireNonNull(stat);
|
|
Objects.requireNonNull(currentHealth);
|
|
Objects.requireNonNull(nativeLimit);
|
|
if (currentHealth.signum() < 0 || nativeLimit.signum() <= 0) {
|
|
throw new IllegalArgumentException("Invalid stat-purchase health bound");
|
|
}
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) {
|
|
return new StatPurchase(StatPurchaseStatus.UNAVAILABLE, Optional.empty());
|
|
}
|
|
var old = found.orElseThrow();
|
|
if (!old.revision().equals(expectedRevision)) {
|
|
return new StatPurchase(StatPurchaseStatus.STALE, Optional.of(old));
|
|
}
|
|
if (old.unspentPoints().signum() == 0) {
|
|
return new StatPurchase(StatPurchaseStatus.NO_POINTS, Optional.of(old));
|
|
}
|
|
var oldMaximum = old.maximumHealth().min(nativeLimit);
|
|
if (currentHealth.compareTo(oldMaximum) > 0) {
|
|
return new StatPurchase(StatPurchaseStatus.STALE, Optional.of(old));
|
|
}
|
|
var stats = new java.util.EnumMap<Stat, BigInteger>(Stat.class);
|
|
stats.putAll(old.stats());
|
|
stats.put(stat, stats.get(stat).add(BigInteger.ONE));
|
|
var rawMaximum = new java.math.BigDecimal(stats.get(Stat.CON).add(BigInteger.TEN));
|
|
var gain = rawMaximum.min(nativeLimit).subtract(oldMaximum);
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), stats,
|
|
old.level(), old.experience(), old.unspentPoints().subtract(BigInteger.ONE),
|
|
currentHealth.add(gain), old.learned(), old.loadout(), old.passives(), old.cooldowns(), old.restrictedKills(), false,
|
|
old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return new StatPurchase(StatPurchaseStatus.APPLIED, Optional.of(saved));
|
|
});
|
|
}
|
|
|
|
/** Session-owned remaining health; retain all other current fields and reject concurrent revision changes. */
|
|
public CompletableFuture<Optional<CharacterRecord>> saveHealth(UUID characterId, java.math.BigDecimal health,
|
|
java.math.BigDecimal nativeLimit) {
|
|
return saveHealth(characterId, null, health, nativeLimit);
|
|
}
|
|
|
|
/** Ability-owned health mutation that refuses a changed character revision rather than healing stale state. */
|
|
public CompletableFuture<Optional<CharacterRecord>> saveHealth(UUID characterId, BigInteger expectedRevision,
|
|
java.math.BigDecimal health, java.math.BigDecimal nativeLimit) {
|
|
Objects.requireNonNull(characterId);
|
|
if (health.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
|
|
return submit(() -> {
|
|
var found = repository.load(characterId);
|
|
if (found.isEmpty() || found.orElseThrow().dead()) return Optional.empty();
|
|
var old = found.orElseThrow();
|
|
if (expectedRevision != null && !old.revision().equals(expectedRevision)) return Optional.empty();
|
|
var bounded = health.min(old.maximumHealth()).min(nativeLimit);
|
|
if (old.health().compareTo(bounded) == 0) return Optional.of(old);
|
|
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
|
old.experience(), old.unspentPoints(), bounded, old.learned(), old.loadout(), old.passives(), old.cooldowns(),
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
|
|
repository.replace(saved, old.revision());
|
|
return Optional.of(saved);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* One accepted defeat against the latest live record on this worker, including queued names.
|
|
* The repository's locked revision compare-and-replace prevents overwriting a concurrent
|
|
* external writer; a conflict fails rather than retrying an uncertain death or reviving it.
|
|
* Callers must retain their one-use session authority until the result resolves.
|
|
*/
|
|
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId) {
|
|
return death(characterId, null, false);
|
|
}
|
|
|
|
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId, BigInteger expectedRevision) {
|
|
return death(characterId, Objects.requireNonNull(expectedRevision), false);
|
|
}
|
|
|
|
public CompletableFuture<Optional<CharacterRecord>> recordDeath(UUID characterId, boolean loseCoins) {
|
|
return death(characterId, null, loseCoins);
|
|
}
|
|
|
|
/** Finalize one claimed downed outcome with its stable death identity and original resolution time. */
|
|
public CompletableFuture<Optional<CharacterRecord>> recordFinalDeath(UUID characterId,BigInteger expectedRevision,UUID deathId,Instant diedAt,boolean loseCoins){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(deathId);Objects.requireNonNull(diedAt);return submit(()->{var found=repository.load(characterId);if(found.isEmpty())return Optional.empty();var old=found.orElseThrow();if(old.dead())return old.deathId().equals(deathId)&&old.diedAt().equals(diedAt)?Optional.of(old):Optional.empty();if(!old.revision().equals(expectedRevision))return Optional.empty();var dead=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints(),java.math.BigDecimal.ZERO,old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),true,deathId,diedAt,loseCoins?BigInteger.ZERO:old.coins(),old.coinsInitialized(),old.rewardReceipts(),loseCoins?old.coins():BigInteger.ZERO,old.gear(),old.sheetGeneration());repository.replace(dead,old.revision());var bridge=coinEvents;if(bridge!=null&&loseCoins&&old.coins().signum()>0)bridge.lost(old,dead,deathId,diedAt);return Optional.of(dead);});}
|
|
|
|
private CompletableFuture<Optional<CharacterRecord>> death(UUID characterId, BigInteger expectedRevision, boolean loseCoins) {
|
|
Objects.requireNonNull(characterId);
|
|
Instant diedAt = clock.instant();
|
|
UUID deathId = UUID.randomUUID();
|
|
return submit(() -> {
|
|
Optional<CharacterRecord> found = repository.load(characterId);
|
|
if (found.isEmpty()) return Optional.empty();
|
|
CharacterRecord old = found.orElseThrow();
|
|
if (old.dead() || expectedRevision != null && !old.revision().equals(expectedRevision)) return Optional.empty();
|
|
var dead = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
|
old.level(), old.experience(), old.unspentPoints(), java.math.BigDecimal.ZERO, old.learned(),
|
|
old.loadout(), old.passives(), old.cooldowns(), old.restrictedKills(), true, deathId, diedAt,
|
|
loseCoins ? BigInteger.ZERO : old.coins(), old.coinsInitialized(), old.rewardReceipts(),
|
|
loseCoins ? old.coins() : BigInteger.ZERO,old.gear(),old.sheetGeneration());
|
|
repository.replace(dead, old.revision());
|
|
return Optional.of(dead);
|
|
});
|
|
}
|
|
|
|
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId) {
|
|
return restoreDeathRecord(characterId, deathId, null);
|
|
}
|
|
|
|
/** Native Revive supplies the current plugin-controlled health ceiling captured on the server thread. */
|
|
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecord(UUID characterId, UUID deathId,
|
|
java.math.BigDecimal nativeLimit) {
|
|
return restore(characterId, deathId, nativeLimit, true);
|
|
}
|
|
|
|
/** Administrator revival retains death identity/consume-once checks but deliberately ignores death age. */
|
|
public CompletableFuture<Optional<CharacterRecord>> restoreDeathRecordAdministratively(
|
|
UUID characterId, UUID deathId, java.math.BigDecimal nativeLimit) {
|
|
return restore(characterId, deathId, nativeLimit, false);
|
|
}
|
|
|
|
private CompletableFuture<Optional<CharacterRecord>> restore(UUID characterId, UUID deathId,
|
|
java.math.BigDecimal nativeLimit, boolean ageLimited) {
|
|
Objects.requireNonNull(characterId); Objects.requireNonNull(deathId);
|
|
if (nativeLimit != null && nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid revival health limit");
|
|
Instant selectedAt = clock.instant();
|
|
return submit(() -> {
|
|
Optional<CharacterRecord> found = repository.load(characterId);
|
|
if (found.isEmpty() || !found.orElseThrow().dead()) return Optional.empty();
|
|
CharacterRecord old = found.orElseThrow();
|
|
Duration age = Duration.between(old.diedAt(), selectedAt);
|
|
if (!deathId.equals(old.deathId()) || age.isNegative()
|
|
|| ageLimited && age.compareTo(Duration.ofHours(24)) >= 0) return Optional.empty();
|
|
var health = nativeLimit == null ? old.maximumHealth() : old.maximumHealth().min(nativeLimit);
|
|
var restored = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(),
|
|
old.level(), old.experience(), old.unspentPoints(), health, old.learned(), old.loadout(), old.passives(), old.cooldowns(),
|
|
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),BigInteger.ZERO,old.gear(),old.sheetGeneration());
|
|
repository.replace(restored, old.revision());
|
|
return Optional.of(restored);
|
|
});
|
|
}
|
|
|
|
@FunctionalInterface
|
|
private interface DiskOperation<T> { T run() throws IOException; }
|
|
|
|
private <T> CompletableFuture<T> submit(DiskOperation<T> operation) {
|
|
try {
|
|
return CompletableFuture.supplyAsync(() -> {
|
|
try {
|
|
return operation.run();
|
|
} catch (IOException exception) {
|
|
throw new CompletionException(exception);
|
|
}
|
|
}, worker);
|
|
} catch (RejectedExecutionException exception) {
|
|
return CompletableFuture.failedFuture(exception);
|
|
}
|
|
}
|
|
|
|
/** Stop accepting work without blocking shutdown; already queued file writes may finish. */
|
|
@Override
|
|
public void close() {
|
|
worker.shutdown();
|
|
}
|
|
}
|