feat(crafting): retain ownership through async craft saves
Release / release (push) Successful in 4m58s
CI / build (push) Successful in 2m33s

This commit is contained in:
dmg committed 2026-09-17 22:47:35 -04:00
1 parent f4cb7a3914
commit 3215697e3f
4 files changed
+592 -2

No files matched your search

@@ -5,6 +5,10 @@ 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;
@@ -33,6 +37,152 @@ public final class CharacterStorage implements AutoCloseable {
});
}
/**
* 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) {
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.cooldowns().isEmpty()
|| record.loadout().stream().anyMatch(ability -> !ability.isEmpty())) {
throw new IllegalArgumentException("Craft batch requires distinct new characters");
}
}
return new CraftPreparation(snapshot);
}
public final class CraftPreparation {
private final List<CharacterRecord> requested;
private final CompletableFuture<CraftBatch> completion;
private volatile boolean abandoned;
private CompletableFuture<CraftCleanup> cleanup;
private CraftPreparation(List<CharacterRecord> records) {
requested = records;
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();
}
/** 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();
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 CompletableFuture<Optional<CharacterRecord>> find(UUID id) {
return submit(() -> repository.load(id));
}
@@ -11,6 +11,8 @@ import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@@ -37,13 +39,32 @@ public final class YamlCharacterRepository {
}
public void create(CharacterRecord character) throws IOException {
createTracked(character);
}
/** Process-local proof; never reconstructed from a revision-zero file after restart. */
static final class Creation {
final CharacterRecord record;
private final BasicFileAttributes attributes;
private final byte[] bytes;
private Creation(CharacterRecord record, BasicFileAttributes attributes, byte[] bytes) {
this.record = record;
this.attributes = attributes;
this.bytes = bytes;
}
}
Creation createTracked(CharacterRecord character) throws IOException {
if (character.revision().signum() != 0) throw new IOException("New character revision must be zero");
Creation[] created = new Creation[1];
withLock(character.id(), () -> {
if (Files.exists(file(character.id()), LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Character already exists: " + character.id());
}
write(character);
created[0] = write(character);
});
return created[0];
}
public void replace(CharacterRecord character, BigInteger expectedRevision) throws IOException {
@@ -57,6 +78,31 @@ public final class YamlCharacterRepository {
});
}
/** Only the in-memory creator of a never-issued batch may request this cleanup. */
boolean discardUnissued(Creation created) throws IOException {
boolean[] removed = {false};
withLock(created.record.id(), () -> {
var path = file(created.record.id());
if (Files.notExists(path, LinkOption.NOFOLLOW_LINKS)) {
removed[0] = true;
return;
}
var current = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
var expected = created.attributes;
if (!current.isRegularFile() || expected.fileKey() == null
|| !expected.fileKey().equals(current.fileKey())
|| !expected.creationTime().equals(current.creationTime())
|| !expected.lastModifiedTime().equals(current.lastModifiedTime())
|| current.size() != created.bytes.length) return;
try (var input = Files.newInputStream(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
if (!Arrays.equals(created.bytes, input.readNBytes(created.bytes.length + 1))) return;
}
Files.delete(path);
removed[0] = true;
});
return removed[0];
}
public Optional<CharacterRecord> load(UUID id) throws IOException {
Path file = file(id);
if (Files.notExists(file, LinkOption.NOFOLLOW_LINKS)) return Optional.empty();
@@ -73,7 +119,7 @@ public final class YamlCharacterRepository {
}
}
private void write(CharacterRecord character) throws IOException {
private Creation write(CharacterRecord character) throws IOException {
byte[] bytes = CharacterYaml.encode(character).getBytes(StandardCharsets.UTF_8);
if (bytes.length > MAX_FILE_BYTES) throw new IOException("Character YAML exceeds the safe file-size limit");
Path temporary = Files.createTempFile(directory, ".character-", ".tmp");
@@ -83,8 +129,10 @@ public final class YamlCharacterRepository {
while (buffer.hasRemaining()) output.write(buffer);
output.force(true);
}
var attributes = Files.readAttributes(temporary, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
// Never fall back to an in-place, partially written character record.
replacement.move(temporary, file(character.id()));
return new Creation(character, attributes, bytes);
} finally {
Files.deleteIfExists(temporary);
}