fix(health-steal): bound healing and retain recovery proof
This commit is contained in:
1 parent
d4ae188501
commit
403dd4b78a
7 files changed
+851
-16
No files matched your search
@@ -169,6 +169,13 @@ public final class HealthSteal implements Listener, AutoCloseable {
|
||||
if (healing.isCancelled() || !Double.isFinite(accepted) || accepted <= 0) {
|
||||
if (events != null) events.refused(audit, healing.isCancelled() ? "native_event_cancelled" : "no_positive_healing_accepted"); return;
|
||||
}
|
||||
var validated = sessions.currentRecord(active).orElse(null);
|
||||
var validatedMaximum = player.getAttribute(Attribute.MAX_HEALTH);
|
||||
if (!sessions.current(active) || validated == null || !validated.revision().equals(record.revision())
|
||||
|| Double.compare(player.getHealth(), current) != 0 || validatedMaximum == null
|
||||
|| Double.compare(Math.min(validatedMaximum.getValue(), validated.maximumHealth().doubleValue()), maximum) != 0) {
|
||||
if (events != null) events.refused(audit, "native_healing_context_changed"); return;
|
||||
}
|
||||
var queue = pending.computeIfAbsent(active.character(), ignored -> new ArrayDeque<>());
|
||||
if (queue.size() >= MAX_PENDING_PER_CHARACTER) { if (events != null) events.refused(audit, "pending_heal_capacity"); return; }
|
||||
queue.addLast(new Heal(active, accepted, audit));
|
||||
@@ -185,46 +192,148 @@ public final class HealthSteal implements Listener, AutoCloseable {
|
||||
auditFailed(operation, "character_unavailable_or_passive_removed"); finish(character); return;
|
||||
}
|
||||
double nativeBefore = player.getHealth();
|
||||
BigDecimal target = record.health().add(BigDecimal.valueOf(operation.amount()));
|
||||
var attribute = player.getAttribute(Attribute.MAX_HEALTH);
|
||||
double maximum = attribute == null ? Double.NaN : Math.min(attribute.getValue(), record.maximumHealth().doubleValue());
|
||||
if (!Double.isFinite(nativeBefore) || nativeBefore <= 0 || !Double.isFinite(maximum) || nativeBefore >= maximum) {
|
||||
auditFailed(operation, "no_current_native_healing_capacity"); finish(character); return;
|
||||
}
|
||||
BigDecimal limit;
|
||||
try { limit = nativeLimit.get(); }
|
||||
catch (RuntimeException failure) { auditFailed(operation, "native_health_limit_unavailable"); report(character, failure); finish(character); return; }
|
||||
// Native combat, not stale saved health, supplies the baseline. The native pool stores floats:
|
||||
// persist a representable target rounded down so publication cannot amplify the accepted budget.
|
||||
double bounded = Math.min(maximum, Math.min(limit.doubleValue(), nativeBefore + operation.amount()));
|
||||
float nativeTarget = (float) bounded;
|
||||
if (!Float.isFinite(nativeTarget)) nativeTarget = Float.MAX_VALUE;
|
||||
if (nativeTarget > bounded || (double) nativeTarget - nativeBefore > operation.amount())
|
||||
nativeTarget = Math.nextDown(nativeTarget);
|
||||
if (nativeTarget <= nativeBefore) {
|
||||
auditFailed(operation, "no_positive_representable_heal"); finish(character); return;
|
||||
}
|
||||
BigDecimal target = BigDecimal.valueOf((double) nativeTarget);
|
||||
BigInteger expected = record.revision();
|
||||
characters.saveHealth(character, expected, target, limit).whenComplete((saved, failure) -> {
|
||||
try { nextTick.accept(() -> complete(character, operation, expected, record, nativeBefore, saved, failure)); }
|
||||
var completed = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
characters.prepareHealthStealHealth(character, expected, target, limit).whenComplete((saved, failure) -> {
|
||||
try { nextTick.accept(() -> {
|
||||
if (completed.compareAndSet(false, true))
|
||||
complete(character, operation, expected, record, nativeBefore, maximum, saved, failure);
|
||||
}); }
|
||||
catch (RuntimeException rejected) { auditFailed(operation, "scheduler_rejected_after_save_uncertain"); report(character, rejected); }
|
||||
});
|
||||
}
|
||||
|
||||
private void complete(UUID character, Heal operation, BigInteger expected, CharacterRecord before, double nativeBefore,
|
||||
java.util.Optional<CharacterRecord> saved, Throwable failure) {
|
||||
double capturedMaximum, java.util.Optional<CharacterStorage.PendingHealthSteal> saved, Throwable failure) {
|
||||
CharacterRecord repair = null;
|
||||
try {
|
||||
if (closed || failure != null || saved == null || saved.isEmpty()) {
|
||||
auditFailed(operation, closed ? "closed_after_save" : failure != null ? "health_save_failed" : "character_unavailable");
|
||||
if (failure != null) report(character, failure); return;
|
||||
}
|
||||
var record = saved.orElseThrow();
|
||||
var proof = saved.orElseThrow(); var record = proof.saved();
|
||||
// An already matching saved target is a successful no-op save, not a new revision.
|
||||
boolean unchanged = record.equals(before) && sessions.currentRecord(operation.active()).filter(before::equals).isPresent();
|
||||
if (!sessions.current(operation.active())
|
||||
|| !sessions.acknowledgeProgress(operation.active(), expected, record)) {
|
||||
auditFailed(operation, "saved_but_session_publication_refused"); return;
|
||||
|| !(unchanged || sessions.acknowledgeProgress(operation.active(), expected, record))) {
|
||||
repair = record; auditFailed(operation, "saved_but_session_publication_refused"); return;
|
||||
}
|
||||
var player = sessions.currentPlayer(operation.active()).orElse(null);
|
||||
if (player == null || Double.compare(player.getHealth(), nativeBefore) != 0) {
|
||||
auditFailed(operation, "saved_but_native_health_changed"); return;
|
||||
repair = record; auditFailed(operation, "saved_but_native_health_changed"); return;
|
||||
}
|
||||
var attribute = player.getAttribute(Attribute.MAX_HEALTH);
|
||||
if (attribute == null) { auditFailed(operation, "saved_but_maximum_health_unavailable"); return; }
|
||||
if (attribute == null) { repair = record; auditFailed(operation, "saved_but_maximum_health_unavailable"); return; }
|
||||
double maximum = Math.min(attribute.getValue(), record.maximumHealth().doubleValue());
|
||||
double publish = Math.min(maximum, record.health().doubleValue());
|
||||
if (Double.isFinite(maximum) && Double.isFinite(publish) && publish > nativeBefore) {
|
||||
if (!Double.isFinite(maximum) || Double.compare(maximum, capturedMaximum) != 0) {
|
||||
repair = record; auditFailed(operation, "saved_but_maximum_health_changed"); return;
|
||||
}
|
||||
double publish = Math.min(maximum, Math.min(record.health().doubleValue(), nativeBefore + operation.amount()));
|
||||
if (Double.isFinite(publish) && publish > nativeBefore && Double.compare(publish, record.health().doubleValue()) == 0) {
|
||||
try { player.setHealth(publish); }
|
||||
catch (RuntimeException nativeFailure) { auditFailed(operation, "native_health_publication_failed"); throw nativeFailure; }
|
||||
catch (RuntimeException nativeFailure) {
|
||||
repair = record; auditFailed(operation, "native_health_publication_failed"); throw nativeFailure;
|
||||
}
|
||||
// A setter call alone is not proof of the actual native result or retained session authority.
|
||||
if (Double.compare(player.getHealth(), publish) != 0
|
||||
|| sessions.currentRecord(operation.active()).filter(record::equals).isEmpty()) {
|
||||
repair = record; auditFailed(operation, "native_health_publication_unconfirmed"); return;
|
||||
}
|
||||
retire(character, proof, record);
|
||||
if (events != null) events.healed(operation.audit(), before, record, nativeBefore, publish, maximum, operation.amount());
|
||||
if (feedback != null) feedback.report("Health Steal", player, AbilityReport.Type.HEALING, player,
|
||||
BigDecimal.valueOf(publish - nativeBefore).stripTrailingZeros());
|
||||
} else auditFailed(operation, "saved_but_no_positive_native_heal");
|
||||
} finally { finish(character); }
|
||||
} else { repair = record; auditFailed(operation, "saved_but_no_positive_native_heal"); }
|
||||
} finally {
|
||||
if (repair == null) finish(character); else reconcile(character, operation, saved.orElseThrow(), repair, 2);
|
||||
}
|
||||
}
|
||||
|
||||
/** Repair only our saved health in the same session. Preserve newer health and all unrelated progress. No native replay. */
|
||||
private void reconcile(UUID character, Heal operation, CharacterStorage.PendingHealthSteal proof,
|
||||
CharacterRecord committed, int retries) {
|
||||
var player = sessions.currentPlayer(operation.active()).orElse(null);
|
||||
var snapshot = sessions.currentRecord(operation.active()).orElse(null);
|
||||
if (closed || player == null || snapshot == null || snapshot.revision().compareTo(committed.revision()) < 0
|
||||
|| snapshot.health().compareTo(committed.health()) != 0) {
|
||||
finish(character); return;
|
||||
}
|
||||
try {
|
||||
double current = player.getHealth();
|
||||
var attribute = player.getAttribute(Attribute.MAX_HEALTH);
|
||||
double maximum = attribute == null ? Double.NaN : Math.min(attribute.getValue(), snapshot.maximumHealth().doubleValue());
|
||||
if (!Double.isFinite(current) || current < 0 || !Double.isFinite(maximum) || maximum <= 0)
|
||||
throw new IllegalStateException("Native health unavailable for reconciliation");
|
||||
var completed = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
characters.reconcileHealthStealHealth(proof, snapshot, BigDecimal.valueOf(current),
|
||||
nativeLimit.get().min(BigDecimal.valueOf(maximum)))
|
||||
.whenComplete((saved, failure) -> {
|
||||
try {
|
||||
nextTick.accept(() -> {
|
||||
if (!completed.compareAndSet(false, true)) return;
|
||||
boolean retry = false;
|
||||
try {
|
||||
if (failure != null) report(character, failure);
|
||||
else if (saved == null || saved.isEmpty()) {
|
||||
// A combat reward can advance the revision while retaining our health.
|
||||
// Retry only a newly acknowledged snapshot, bounded; never retry a heal or an uncertain write.
|
||||
retry = retries > 0 && sessions.currentRecord(operation.active())
|
||||
.filter(value -> value.revision().compareTo(snapshot.revision()) > 0
|
||||
&& value.health().compareTo(committed.health()) == 0).isPresent();
|
||||
if (!retry) report(character, new IllegalStateException("Health reconciliation revision refused"));
|
||||
} else if (!closed && sessions.current(operation.active())) {
|
||||
var record = saved.orElseThrow();
|
||||
boolean unchanged = record.equals(snapshot)
|
||||
&& sessions.currentRecord(operation.active()).filter(snapshot::equals).isPresent();
|
||||
if (Double.compare(record.health().doubleValue(), current) == 0
|
||||
&& nativeContext(operation, current, maximum)
|
||||
&& (unchanged || sessions.acknowledgeProgress(operation.active(), snapshot.revision(), record))
|
||||
&& nativeContext(operation, current, maximum)) retire(character, proof, record);
|
||||
else report(character, new IllegalStateException("Health reconciliation publication refused"));
|
||||
}
|
||||
} finally {
|
||||
if (retry) reconcile(character, operation, proof, committed, retries - 1); else finish(character);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException rejected) { report(character, rejected); }
|
||||
});
|
||||
} catch (RuntimeException failure) { report(character, failure); finish(character); }
|
||||
}
|
||||
private boolean nativeContext(Heal operation, double health, double maximum) {
|
||||
if (closed || !sessions.current(operation.active())) return false;
|
||||
var player = sessions.currentPlayer(operation.active()).orElse(null);
|
||||
var record = sessions.currentRecord(operation.active()).orElse(null);
|
||||
var attribute = player == null ? null : player.getAttribute(Attribute.MAX_HEALTH);
|
||||
return record != null && attribute != null && Double.compare(player.getHealth(), health) == 0
|
||||
&& Double.compare(Math.min(attribute.getValue(), record.maximumHealth().doubleValue()), maximum) == 0;
|
||||
}
|
||||
|
||||
private void retire(UUID character, CharacterStorage.PendingHealthSteal proof, CharacterRecord settled) {
|
||||
characters.completeHealthStealHealth(proof, settled).whenComplete((completed, failure) -> {
|
||||
if (failure != null || !Boolean.TRUE.equals(completed))
|
||||
report(character, failure != null ? failure : new IllegalStateException("Health Steal proof cleanup unconfirmed; later entry remains blocked"));
|
||||
});
|
||||
}
|
||||
|
||||
private void auditFailed(Heal operation, String reason) { if (events != null) events.failed(operation.audit(), reason); }
|
||||
|
||||
private void finish(UUID character) {
|
||||
|
||||
@@ -28,6 +28,7 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
private final java.util.random.RandomGenerator coinRandom;
|
||||
private final CharacterRecoveryStore recoveries;
|
||||
private final SecondWindHealthStore secondWindHealth;
|
||||
private final HealthStealHealthStore healthStealHealth;
|
||||
private games.dmg.fantasystick.events.CharacterRecoveryEventBridge recoveryEvents;
|
||||
|
||||
public void attachRecoveryEvents(games.dmg.fantasystick.events.CharacterRecoveryEventBridge bridge) {
|
||||
@@ -88,6 +89,7 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
this.coinRandom = Objects.requireNonNull(coinRandom);
|
||||
this.recoveries = new CharacterRecoveryStore(repository.pluginDataDirectory());
|
||||
this.secondWindHealth = new SecondWindHealthStore(repository.pluginDataDirectory());
|
||||
this.healthStealHealth = new HealthStealHealthStore(repository.pluginDataDirectory());
|
||||
repository.attachMutationUnavailable(recoveries::blocks);
|
||||
}
|
||||
|
||||
@@ -484,6 +486,7 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
/** Persist a legacy character's one-time configured migration roll before exposing it. */
|
||||
private Optional<CharacterRecord> load(UUID id) throws IOException {
|
||||
if (secondWindHealth.blocks(id)) throw new IOException("Second Wind native publication is unresolved; character entry refused");
|
||||
if (healthStealHealth.blocks(id)) throw new IOException("Health Steal native publication is unresolved; character entry refused");
|
||||
var found = repository.load(id);
|
||||
if (found.isEmpty()) {
|
||||
if (recoveries.find(id).filter(operation -> operation.phase() != CharacterRecoveryStore.Phase.DELIVERED).isPresent())
|
||||
@@ -1010,6 +1013,69 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Opaque Health Steal authority, separate from Second Wind and confined to the character worker. */
|
||||
public static final class PendingHealthSteal {
|
||||
private final UUID operation;
|
||||
private final CharacterRecord saved;
|
||||
private CharacterRecord latest;
|
||||
private boolean completed;
|
||||
private PendingHealthSteal(UUID operation, CharacterRecord saved) {
|
||||
this.operation = operation; this.saved = saved; this.latest = saved;
|
||||
}
|
||||
public CharacterRecord saved() { return saved; }
|
||||
}
|
||||
|
||||
public CompletableFuture<Optional<PendingHealthSteal>> prepareHealthStealHealth(UUID characterId,
|
||||
BigInteger expectedRevision, java.math.BigDecimal health, java.math.BigDecimal nativeLimit) {
|
||||
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision);
|
||||
if (health.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
|
||||
return submit(() -> repository.transaction(() -> {
|
||||
if (healthStealHealth.blocks(characterId) || !repository.mutationAvailable(characterId)) return Optional.empty();
|
||||
var found = repository.load(characterId);
|
||||
if (found.isEmpty() || found.orElseThrow().dead()
|
||||
|| !found.orElseThrow().revision().equals(expectedRevision)) return Optional.empty();
|
||||
var old = found.orElseThrow();
|
||||
var saved = withHealth(old, health.min(old.maximumHealth()).min(nativeLimit));
|
||||
var operation = UUID.randomUUID();
|
||||
healthStealHealth.prepare(characterId, operation);
|
||||
if (saved != old) repository.replaceLocked(saved, expectedRevision, true);
|
||||
return Optional.of(new PendingHealthSteal(operation, saved));
|
||||
}));
|
||||
}
|
||||
|
||||
/** Preserve newer unrelated progress only under its exact acknowledged snapshot and our still-owned health. */
|
||||
public CompletableFuture<Optional<CharacterRecord>> reconcileHealthStealHealth(PendingHealthSteal pending,
|
||||
CharacterRecord expected, java.math.BigDecimal observedHealth, java.math.BigDecimal nativeLimit) {
|
||||
Objects.requireNonNull(pending); Objects.requireNonNull(expected);
|
||||
if (observedHealth.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
|
||||
return submit(() -> repository.transaction(() -> {
|
||||
if (pending.completed || !pending.saved.id().equals(expected.id()) || expected.dead()
|
||||
|| expected.revision().compareTo(pending.latest.revision()) < 0
|
||||
|| expected.health().compareTo(pending.latest.health()) != 0) return Optional.empty();
|
||||
var id = pending.saved.id();
|
||||
healthStealHealth.verify(id, pending.operation);
|
||||
var found = repository.load(id);
|
||||
if (found.isEmpty() || !found.orElseThrow().equals(expected)) return Optional.empty();
|
||||
var saved = withHealth(expected, observedHealth.min(expected.maximumHealth()).min(nativeLimit));
|
||||
if (saved != expected) repository.replaceLocked(saved, expected.revision(), true);
|
||||
pending.latest = saved;
|
||||
return Optional.of(saved);
|
||||
}));
|
||||
}
|
||||
|
||||
/** A native acknowledgment cannot clear another operation's proof or a newer, unacknowledged record. */
|
||||
public CompletableFuture<Boolean> completeHealthStealHealth(PendingHealthSteal pending, CharacterRecord settled) {
|
||||
Objects.requireNonNull(pending); Objects.requireNonNull(settled);
|
||||
return submit(() -> repository.transaction(() -> {
|
||||
if (pending.completed || !pending.latest.equals(settled)) return false;
|
||||
healthStealHealth.verify(pending.saved.id(), pending.operation);
|
||||
if (repository.load(pending.saved.id()).filter(settled::equals).isEmpty()) return false;
|
||||
healthStealHealth.complete(pending.saved.id(), pending.operation);
|
||||
pending.completed = true;
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
private static CharacterRecord withHealth(CharacterRecord old, java.math.BigDecimal bounded) {
|
||||
if (old.health().compareTo(bounded) == 0) return old;
|
||||
return new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Unresolved native-publication proof is a load barrier, never permission to replay a heal. */
|
||||
final class HealthStealHealthStore {
|
||||
private final Path directory;
|
||||
|
||||
HealthStealHealthStore(Path pluginDataDirectory) {
|
||||
directory = pluginDataDirectory.resolve("health-steal-health").toAbsolutePath();
|
||||
}
|
||||
|
||||
boolean blocks(UUID character) throws IOException {
|
||||
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) return false;
|
||||
safeDirectory();
|
||||
// Unknown, malformed, unreadable and symlink proof all remain unresolved.
|
||||
return !Files.notExists(file(character), LinkOption.NOFOLLOW_LINKS);
|
||||
}
|
||||
|
||||
/** Caller holds the character repository lock through proof and character replacement. */
|
||||
void prepare(UUID character, UUID operation) throws IOException {
|
||||
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.createDirectory(directory);
|
||||
DurableFiles.forceDirectory(directory.getParent());
|
||||
}
|
||||
safeDirectory();
|
||||
byte[] bytes = operation.toString().getBytes(StandardCharsets.UTF_8);
|
||||
try (var channel = FileChannel.open(file(character), StandardOpenOption.CREATE_NEW,
|
||||
StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var buffer = ByteBuffer.wrap(bytes);
|
||||
while (buffer.hasRemaining()) channel.write(buffer);
|
||||
channel.force(true);
|
||||
}
|
||||
DurableFiles.forceDirectory(directory);
|
||||
}
|
||||
|
||||
void verify(UUID character, UUID operation) throws IOException {
|
||||
safeDirectory();
|
||||
var path = file(character);
|
||||
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) != 36)
|
||||
throw new IOException("Health Steal publication proof is unsafe or missing");
|
||||
try (var channel = FileChannel.open(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||
var bytes = ByteBuffer.allocate(37);
|
||||
while (bytes.hasRemaining() && channel.read(bytes) > 0) { /* Bound proof reads. */ }
|
||||
bytes.flip();
|
||||
if (!StandardCharsets.UTF_8.decode(bytes).toString().equals(operation.toString()))
|
||||
throw new IOException("Health Steal publication proof does not match its operation");
|
||||
}
|
||||
}
|
||||
|
||||
void complete(UUID character, UUID operation) throws IOException {
|
||||
verify(character, operation);
|
||||
Files.delete(file(character));
|
||||
DurableFiles.forceDirectory(directory);
|
||||
}
|
||||
|
||||
private Path file(UUID character) { return directory.resolve(character + ".pending"); }
|
||||
|
||||
private void safeDirectory() throws IOException {
|
||||
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS))
|
||||
throw new IOException("Health Steal publication directory is unsafe");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user