Merge studio hotload time into dirty hotloads

- Keep the stand-in path for new custom biomes over the blocked hotload
- Drop RegistryRestartRequiredException and the blocked restart message
- Remove the duplicate restart notice keys from the locale files
This commit is contained in:
piexel committed 2026-11-30 22:02:21 +01:00
commit 6a7895b15d
57 files changed
+1552 -231

No files matched your search

@@ -401,6 +401,7 @@ public class IrisSettings {
public static class IrisSettingsStudio {
public boolean openVSCode = true;
public boolean blendChanges = true;
public boolean validateBeforeHotload = false;
public boolean disableTimeAndWeather = true;
public boolean entitySpawning = true;
public boolean autoStartDefaultStudio = false;
@@ -0,0 +1,16 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.PackTreeState;
import java.util.Optional;
/**
* The Studio source state an activated epoch was snapshotted from. While that epoch is still active, source files
* whose size and modification time match it are known to equal the epoch's published files.
*/
record ActivatedStudioSource(String epochId, PackTreeState sourceState) {
Optional<PackTreeState> sourceStateOf(GenerationEpoch active) {
return active.epochId().equals(epochId) ? Optional.of(sourceState) : Optional.empty();
}
}
@@ -27,6 +27,7 @@ import art.arcane.iris.generation.runtime.IrisEngine.LifecycleState;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.world.history.GenerationActivation;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.IrisBoundarySignatureSampler;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
@@ -50,6 +51,7 @@ import static art.arcane.iris.generation.runtime.EngineShutdownSequence.runClean
final class EngineHotloader {
private final IrisEngine engine;
private final Object studioTransitionLock = new Object();
private ActivatedStudioSource activatedStudioSource;
EngineHotloader(IrisEngine engine) {
this.engine = engine;
@@ -235,7 +237,8 @@ final class EngineHotloader {
long startedAt = System.nanoTime();
engine.requireRunning("hotload the Studio pack");
GenerationHistory history = router.history();
update = StudioGenerationUpdate.prepare(engine, history);
StudioPackValidation validation = StudioPackValidation.configured();
update = StudioGenerationUpdate.prepare(engine, history, activatedStudioSource, validation);
if (update == null) {
return;
}
@@ -264,11 +267,11 @@ final class EngineHotloader {
IrisSettings settings = IrisSettings.get();
int transitionWidth = settings.getStudio().isBlendChanges()
? settings.getGenerator().getGenerationTransitionWidthBlocks() : 0;
history.stageUpdate(update.source(), update.fingerprint(), update.dimensionContract(),
history.stageVerifiedUpdate(update.pack(), update.dimensionContract(),
update.registryContract(), transitionWidth);
}
long stagedAt = System.nanoTime();
cutover.promotePending();
GenerationActivation activated = cutover.promotePending();
long promotedAt = System.nanoTime();
synchronized (engine.lifecycleLock) {
if (engine.lifecycleState != LifecycleState.HOTLOADING) {
@@ -290,6 +293,10 @@ final class EngineHotloader {
StudioRestartRequirement requirement = StudioRestartRequirement.pending(update.pendingBiomes());
publishRestartRequirement(requirement);
broadcastStudioHotload(false, restartNote(requirement));
activatedStudioSource = update.activatedAs(activated.epochId());
if (validation == StudioPackValidation.AFTER_ACTIVATION) {
auditActivatedPack(history, activated);
}
} catch (Throwable failure) {
if (previous != null) {
synchronized (engine.lifecycleLock) {
@@ -337,6 +344,18 @@ final class EngineHotloader {
}
}
/**
* Never throws: it runs after the activation is durable, where any failure would mark the engine failed.
*/
private void auditActivatedPack(GenerationHistory history, GenerationActivation activated) {
try {
new StudioPackAudit(engine, history, activated.epochId(), message -> broadcastStudioHotload(true, message))
.runInBackground();
} catch (Throwable auditFailure) {
IrisLogging.reportError("Failed to start the Studio pack validation.", auditFailure);
}
}
private void publishRestartRequirement(StudioRestartRequirement requirement) {
engine.studioRestartRequirement = requirement;
if (requirement.isPending()) {
@@ -7,11 +7,12 @@ import art.arcane.iris.pack.AtomicDirectoryPublisher;
import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.GenerationEpochContractFactory;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationPackFingerprint;
import art.arcane.iris.world.history.GenerationPackRepository;
import art.arcane.iris.world.history.GenerationRegistryContract;
import art.arcane.iris.world.history.GenerationRegistryContractFactory;
import art.arcane.iris.world.history.PackTreeState;
import art.arcane.iris.world.history.StudioRegistryCapture;
import art.arcane.iris.world.history.VerifiedPackTree;
import art.arcane.iris.generation.terrain.IrisDimension;
import java.io.IOException;
@@ -19,31 +20,44 @@ import java.nio.file.Path;
import java.nio.file.Files;
import java.util.List;
/**
* A Studio pack edit captured as one read-only snapshot inside the world's generation folder. The snapshot is
* hashed once and later moved into the epoch repository as it is.
*/
record StudioGenerationUpdate(
Path stagingRoot,
Path source,
String fingerprint,
VerifiedPackTree pack,
PackTreeState sourceState,
GenerationEpoch.DimensionContract dimensionContract,
GenerationRegistryContract registryContract,
List<String> pendingBiomes
) implements AutoCloseable {
static StudioGenerationUpdate prepare(IrisEngine engine, GenerationHistory history) throws IOException {
private static final String TRIAL_MANTLE_DIRECTORY = ".trial-mantle";
/**
* @param previous the source the active epoch came from, when this engine activated it; without it every file
* is compared by content against the active epoch
* @return null when the source still matches the active epoch
*/
static StudioGenerationUpdate prepare(IrisEngine engine, GenerationHistory history,
ActivatedStudioSource previous, StudioPackValidation validation)
throws IOException {
Path source = engine.getStudioGenerationSource().toRealPath();
IrisData.invalidateLoadedAuthoringResources(source.toFile());
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
GenerationEpoch active = history.activeEpoch();
if (active.packFingerprintVersion() == GenerationPackFingerprint.CURRENT_VERSION
&& fingerprint.equals(active.packFingerprint())) {
PackTreeState sourceState = PackTreeState.capture(source);
PackTreeState activeSourceState = previous == null ? null
: previous.sourceStateOf(history.activeEpoch()).orElse(null);
if (sourceState.equals(activeSourceState)) {
return null;
}
Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-");
Path snapshot = stagingRoot.resolve(source.getFileName());
try {
GenerationPackRepository.copyPackTree(source, snapshot);
if (!fingerprint.equals(GenerationPackFingerprint.compute(snapshot, GenerationPackFingerprint.CURRENT_VERSION))) {
throw new IOException("Studio pack changed while its update snapshot was being captured.");
StudioGenerationUpdate update = prepareStaged(
engine, history, source, sourceState, activeSourceState, stagingRoot, validation);
if (update == null) {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
}
return prepareSnapshot(engine, history, stagingRoot, snapshot, fingerprint);
return update;
} catch (Throwable failure) {
try {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
@@ -54,16 +68,39 @@ record StudioGenerationUpdate(
}
}
private static StudioGenerationUpdate prepareSnapshot(IrisEngine engine, GenerationHistory history,
Path stagingRoot, Path source, String fingerprint)
private static StudioGenerationUpdate prepareStaged(IrisEngine engine, GenerationHistory history, Path source,
PackTreeState sourceState, PackTreeState activeSourceState,
Path stagingRoot, StudioPackValidation validation)
throws IOException {
GenerationEpoch active = history.activeEpoch();
PackValidationResult validation = PackValidator.validate(source.toFile());
if (!validation.isLoadable()) {
throw new IOException("Studio pack update is invalid: " + String.join("; ", validation.getBlockingErrors()));
Path snapshot = stagingRoot.resolve(source.getFileName());
GenerationPackRepository.snapshotPackTree(
source, snapshot, history.activePackLinkBasis().orElse(null), activeSourceState);
VerifiedPackTree pack = VerifiedPackTree.hash(snapshot);
if (isActive(history.activeEpoch(), pack)) {
return null;
}
IrisData data = IrisData.openRuntime(source.toFile());
if (!sourceState.equals(PackTreeState.capture(source))) {
throw new IOException("Studio pack changed while its update snapshot was being captured.");
}
return prepareSnapshot(engine, history, stagingRoot, pack, sourceState, validation);
}
private static boolean isActive(GenerationEpoch active, VerifiedPackTree pack) {
return active.packFingerprintVersion() == pack.fingerprintVersion()
&& active.packFingerprint().equals(pack.fingerprint());
}
private static StudioGenerationUpdate prepareSnapshot(IrisEngine engine, GenerationHistory history,
Path stagingRoot, VerifiedPackTree pack,
PackTreeState sourceState,
StudioPackValidation validation) throws IOException {
GenerationEpoch active = history.activeEpoch();
IrisData data = IrisData.openRuntime(pack.root().toFile());
try {
data.useVerifiedGenerationPackFingerprint(pack.fingerprint());
if (validation == StudioPackValidation.BEFORE_ACTIVATION) {
requireLoadable(pack, data);
}
IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey());
if (replacement == null) {
throw new IOException("Studio pack update is missing dimension '"
@@ -76,17 +113,58 @@ record StudioGenerationUpdate(
throw new IOException("Studio pack update changes the world's immutable dimension layout.");
}
StudioRegistryCapture registry = GenerationRegistryContractFactory.createRetainingLoadedBiomes(
data, replacement, fingerprint, active.registryContract());
data, replacement, pack.fingerprint(), active.registryContract());
GenerationRegistryContract registryContract = registry.contract();
registryContract.requireDefinitionsAvailableIn(
GenerationRegistryContractFactory.captureRequiredDefinitions(List.of(registryContract)));
return new StudioGenerationUpdate(stagingRoot, source, fingerprint, contract, registryContract,
requireBuildableRuntime(engine, data, replacement, registryContract,
stagingRoot.resolve(TRIAL_MANTLE_DIRECTORY));
return new StudioGenerationUpdate(stagingRoot, pack, sourceState, contract, registryContract,
registry.pendingBiomes());
} finally {
data.close();
if (!data.isClosed()) {
data.close();
}
}
}
private static void requireLoadable(VerifiedPackTree pack, IrisData data) throws IOException {
PackValidationResult validation = PackValidator.validate(pack.root().toFile(), data);
if (!validation.isLoadable()) {
throw new IOException("Studio pack update is invalid: " + String.join("; ", validation.getBlockingErrors()));
}
}
/**
* The activation builds its runtime only after the manifest already points at the update, so a pack that cannot
* build there leaves the Studio engine failed. Building and discarding one here rejects such a pack first.
*/
private static void requireBuildableRuntime(IrisEngine engine, IrisData data, IrisDimension dimension,
GenerationRegistryContract registry, Path mantleDirectory)
throws IOException {
data.bindGenerationRegistryContract(registry);
IrisEngine.GenerationRuntimeBinding trial;
try {
trial = engine.buildDetachedGenerationRuntime(
new EngineTarget(engine.getWorld(), dimension, data), mantleDirectory, null);
} catch (RuntimeException failure) {
throw new IOException("Studio pack update cannot build a generation runtime: " + rootCauseMessage(failure), failure);
}
engine.closeDetachedGenerationRuntime(trial);
}
private static String rootCauseMessage(Throwable failure) {
Throwable cause = failure;
while (cause.getCause() != null && cause.getCause() != cause) {
cause = cause.getCause();
}
return cause.getClass().getSimpleName() + ": " + cause.getMessage();
}
ActivatedStudioSource activatedAs(String epochId) {
return new ActivatedStudioSource(epochId, sourceState);
}
@Override
public void close() throws IOException {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
@@ -0,0 +1,73 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.world.history.GenerationHistory;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
/**
* Runs the full pack validator against an activated Studio epoch after the hotload, so authoring mistakes the
* activation gate does not cover are still reported without holding up the cutover.
*/
final class StudioPackAudit {
private static final int LOGGED_WARNING_LIMIT = 3;
private final IrisEngine engine;
private final GenerationHistory history;
private final String epochId;
private final Consumer<String> blockingErrorReport;
StudioPackAudit(IrisEngine engine, GenerationHistory history, String epochId, Consumer<String> blockingErrorReport) {
this.engine = engine;
this.history = history;
this.epochId = epochId;
this.blockingErrorReport = blockingErrorReport;
}
CompletableFuture<Void> runInBackground() {
return MultiBurst.burst.completeValueAsync(this::validate)
.thenAccept(this::report)
.exceptionally(failure -> {
if (!engine.isClosed()) {
IrisLogging.reportError("Studio pack validation failed for '" + packKey() + "'.", failure);
}
return null;
});
}
private PackValidationResult validate() {
Path pack = history.paths().packRoot(epochId);
return PackValidator.validate(pack.toFile());
}
void report(PackValidationResult result) {
if (engine.isClosed() || !history.activeEpoch().epochId().equals(epochId)) {
return;
}
reportWarnings(result.getWarnings());
if (result.isLoadable()) {
return;
}
String errors = String.join("; ", result.getBlockingErrors());
IrisLogging.warn("Studio pack '%s' is active but has blocking validation errors: %s", packKey(), errors);
blockingErrorReport.accept("Pack validation: " + errors);
}
private void reportWarnings(List<String> warnings) {
if (warnings.isEmpty()) {
return;
}
List<String> shown = warnings.subList(0, Math.min(LOGGED_WARNING_LIMIT, warnings.size()));
IrisLogging.warn("Studio pack '%s' has %d validation warnings: %s", packKey(), warnings.size(), String.join("; ", shown));
}
private String packKey() {
return engine.getPackSource().getFileName().toString();
}
}
@@ -0,0 +1,16 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.configuration.IrisSettings;
/**
* When a Studio hotload runs the full pack validator. Before activation an invalid pack is rejected and the hotload
* waits for the validator; after activation the pack goes live first and blocking errors are only reported.
*/
enum StudioPackValidation {
BEFORE_ACTIVATION,
AFTER_ACTIVATION;
static StudioPackValidation configured() {
return IrisSettings.get().getStudio().isValidateBeforeHotload() ? BEFORE_ACTIVATION : AFTER_ACTIVATION;
}
}
@@ -74,6 +74,7 @@ final class IrisLanguageGuide {
Map.entry("befb", "Formatted part of an engine timing label before its bracketed portion."),
Map.entry("before", "Value before the change, or unreachable tree blocks before repair."),
Map.entry("biome", "Name or identifier of the biome being shown."),
Map.entry("biomes", "Biomes whose edits apply only after a server restart."),
Map.entry("block", "Block type or block description being inspected."),
Map.entry("blockX", "X coordinate of the block or teleport destination."),
Map.entry("blockY", "Y coordinate of the block or teleport destination."),
@@ -30,7 +30,6 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -540,7 +539,7 @@ public final class ContentKeyValidator {
boolean inEntities = relative.startsWith("entities/");
JSONObject json;
try {
json = new JSONObject(Files.readString(path, StandardCharsets.UTF_8));
json = PackValidationIo.parseJson(path.toFile());
} catch (Throwable ignored) {
continue;
}
@@ -27,8 +27,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -58,7 +56,7 @@ final class PackDimensionValidator {
String dimensionKey = PackValidationIo.deriveKey(dimensionsFolder, dimFile);
JSONObject dimJson;
try {
dimJson = new JSONObject(Files.readString(dimFile.toPath(), StandardCharsets.UTF_8));
dimJson = PackValidationIo.parseJson(dimFile);
} catch (Throwable e) {
blockingErrors.add("Dimension '" + dimensionKey + "' has invalid JSON: " + e.getMessage());
continue;
@@ -98,7 +96,7 @@ final class PackDimensionValidator {
JSONObject regionJson;
try {
regionJson = new JSONObject(Files.readString(regionFile.toPath(), StandardCharsets.UTF_8));
regionJson = PackValidationIo.parseJson(regionFile);
} catch (Throwable e) {
blockingErrors.add("Region '" + regionKey + "' has invalid JSON: " + e.getMessage());
continue;
@@ -275,7 +273,7 @@ final class PackDimensionValidator {
blockingErrors.add(context + " references missing style snippet '" + reference + "'.");
return;
}
new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
PackValidationIo.parseJson(snippet.file());
} catch (Throwable error) {
blockingErrors.add(context + " references invalid style snippet '" + reference + "': "
+ error.getMessage());
@@ -638,7 +636,7 @@ final class PackDimensionValidator {
return null;
}
try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
return PackValidationIo.parseJson(snippet.file());
} catch (Throwable e) {
return null;
}
@@ -23,8 +23,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
@@ -69,7 +67,7 @@ final class PackGeneratorDuplicateValidator {
String key = PackValidationIo.deriveKey(generatorsFolder, generatorFile);
String fingerprint;
try {
fingerprint = fingerprint(new JSONObject(Files.readString(generatorFile.toPath(), StandardCharsets.UTF_8)));
fingerprint = fingerprint(PackValidationIo.parseJson(generatorFile));
} catch (Throwable e) {
continue;
}
@@ -99,7 +97,7 @@ final class PackGeneratorDuplicateValidator {
for (File biomeFile : PackValidationIo.listJsonRecursive(biomesFolder)) {
JSONObject biome;
try {
biome = new JSONObject(Files.readString(biomeFile.toPath(), StandardCharsets.UTF_8));
biome = PackValidationIo.parseJson(biomeFile);
} catch (Throwable e) {
continue;
}
@@ -131,7 +129,7 @@ final class PackGeneratorDuplicateValidator {
return null;
}
try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
return PackValidationIo.parseJson(snippet.file());
} catch (Throwable e) {
return null;
}
@@ -27,7 +27,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -59,7 +58,7 @@ final class PackSpawnValidator {
String spawnerKey = PackValidationIo.deriveKey(spawnersFolder, spawnerFile);
JSONObject spawner;
try {
spawner = new JSONObject(Files.readString(spawnerFile.toPath(), StandardCharsets.UTF_8));
spawner = PackValidationIo.parseJson(spawnerFile);
} catch (Throwable e) {
blockingErrors.add("Spawner '" + spawnerKey + "' has invalid JSON: " + e.getMessage());
continue;
@@ -147,7 +146,7 @@ final class PackSpawnValidator {
}
try {
new JSONObject(Files.readString(entityFile, StandardCharsets.UTF_8));
PackValidationIo.parseJson(entityFile.toFile());
validEntityFiles.add(entityFile);
} catch (Throwable e) {
String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
@@ -170,7 +169,7 @@ final class PackSpawnValidator {
String biomeKey = PackValidationIo.deriveKey(biomesFolder, biomeFile);
JSONObject biome;
try {
biome = new JSONObject(Files.readString(biomeFile.toPath(), StandardCharsets.UTF_8));
biome = PackValidationIo.parseJson(biomeFile);
} catch (Throwable e) {
blockingErrors.add("Biome '" + biomeKey + "' has invalid JSON: " + e.getMessage());
continue;
@@ -9,7 +9,6 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
@@ -172,7 +171,7 @@ final class PackStaticObjectValidator {
return null;
}
try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
return PackValidationIo.parseJson(snippet.file());
} catch (IOException | RuntimeException e) {
errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage());
return null;
@@ -27,8 +27,6 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
@@ -782,7 +780,7 @@ final class PackStructurePlacementValidator {
String resourceKey,
List<String> blockingErrors) {
try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
return PackValidationIo.parseJson(file);
} catch (IOException | RuntimeException e) {
String reason = e.getMessage();
if (reason == null || reason.isBlank()) {
@@ -23,8 +23,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@@ -68,7 +66,7 @@ final class PackStyledRangeDefaultValidator {
String key = PackValidationIo.deriveKey(resourceFolder, resourceFile);
JSONObject json;
try {
json = new JSONObject(Files.readString(resourceFile.toPath(), StandardCharsets.UTF_8));
json = PackValidationIo.parseJson(resourceFile);
} catch (Throwable e) {
continue;
}
@@ -122,7 +120,7 @@ final class PackStyledRangeDefaultValidator {
return; // Missing snippets are reported by the content-key machinery.
}
try {
range = new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
range = PackValidationIo.parseJson(snippet.file());
via = " (via snippet '" + snippet.key() + "')";
} catch (Throwable e) {
return;
@@ -26,18 +26,51 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream;
public final class PackValidationIo {
private static final ThreadLocal<ValidationRunReads> ACTIVE_RUN = new ThreadLocal<>();
private PackValidationIo() {
}
/**
* Runs one validation pass in which every folder listing and every JSON parse is done once and shared by all
* steps. The shared trees are read-only by contract. Nothing outlives the pass, so the next pass sees edits.
*/
static <T> T withinValidationRun(Supplier<T> validation) {
if (ACTIVE_RUN.get() != null) {
return validation.get();
}
ACTIVE_RUN.set(new ValidationRunReads());
try {
return validation.get();
} finally {
ACTIVE_RUN.remove();
}
}
static JSONObject parseJson(File file) throws IOException {
ValidationRunReads run = ACTIVE_RUN.get();
if (run == null) {
return parseFile(file);
}
return run.parsedJson(file).jsonOrThrow();
}
private static JSONObject parseFile(File file) throws IOException {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
}
static JSONObject readJson(File file) {
try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8));
return parseJson(file);
} catch (IOException | RuntimeException parseFailure) {
// Every folder scanned through readJson is also scanned by a readGraphJson pass
// (validateUnsupportedStructureTransforms / validateStructureStartPools), which records the
@@ -80,6 +113,14 @@ public final class PackValidationIo {
}
static List<File> listJsonRecursive(File root) {
ValidationRunReads run = ACTIVE_RUN.get();
if (run == null) {
return walkJsonFiles(root);
}
return new ArrayList<>(run.jsonFiles(root));
}
private static List<File> walkJsonFiles(File root) {
List<File> out = new ArrayList<>();
try (Stream<Path> stream = Files.walk(root.toPath())) {
stream.filter(Files::isRegularFile)
@@ -124,4 +165,38 @@ public final class PackValidationIo {
}
return keys;
}
private static final class ValidationRunReads {
private final Map<File, List<File>> jsonFilesByRoot = new HashMap<>();
private final Map<Path, ParsedJson> parsedByPath = new HashMap<>();
List<File> jsonFiles(File root) {
return jsonFilesByRoot.computeIfAbsent(root, PackValidationIo::walkJsonFiles);
}
ParsedJson parsedJson(File file) {
return parsedByPath.computeIfAbsent(file.toPath().toAbsolutePath().normalize(),
ignored -> ParsedJson.parse(file));
}
}
private record ParsedJson(JSONObject json, Exception failure) {
static ParsedJson parse(File file) {
try {
return new ParsedJson(parseFile(file), null);
} catch (IOException | RuntimeException failure) {
return new ParsedJson(null, failure);
}
}
JSONObject jsonOrThrow() throws IOException {
if (failure instanceof IOException readFailure) {
throw readFailure;
}
if (failure instanceof RuntimeException parseFailure) {
throw parseFailure;
}
return json;
}
}
}
@@ -83,15 +83,23 @@ public final class PackValidator {
}
public static PackValidationResult validate(File packFolder) {
return validate(packFolder, true);
return validate(packFolder, true, null);
}
/**
* Gates content through {@code loadedPack} instead of a detached loader, so a caller that goes on to build a
* runtime from the same data does not load the pack a second time. The data stays open.
*/
public static PackValidationResult validate(File packFolder, IrisData loadedPack) {
return validate(packFolder, true, Objects.requireNonNull(loadedPack, "loadedPack"));
}
public static PackValidationResult validateForDatapackBootstrap(File packFolder) {
return validate(packFolder, false);
return validate(packFolder, false, null);
}
public static PackValidationResult validateForPackaging(File packFolder) {
return validate(packFolder, false);
return validate(packFolder, false, null);
}
public static void requireValidObjectSettings(File packFolder, String dimensionKey, JSONObject dimension) {
@@ -103,7 +111,13 @@ public final class PackValidator {
}
}
private static PackValidationResult validate(File packFolder, boolean validateLiveRegistries) {
private static PackValidationResult validate(File packFolder, boolean validateLiveRegistries,
IrisData loadedPack) {
return PackValidationIo.withinValidationRun(() -> validateWithinRun(packFolder, validateLiveRegistries, loadedPack));
}
private static PackValidationResult validateWithinRun(File packFolder, boolean validateLiveRegistries,
IrisData loadedPack) {
String packName = packFolder == null ? "<unknown>" : packFolder.getName();
List<String> blockingErrors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
@@ -176,7 +190,7 @@ public final class PackValidator {
? IrisPlatforms.get().minecraftVersion()
: null;
List<CompatFinding> compatFindings = validateLiveRegistries
? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings)
? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings, loadedPack)
: List.of();
// Keys the version gate already names in its own line are not repeated as unknown-key findings.
@@ -199,14 +213,15 @@ public final class PackValidator {
File[] dimensionFiles,
String minecraftVersion,
List<String> blockingErrors,
List<String> warnings
List<String> warnings,
IrisData loadedPack
) {
if (!IrisPlatforms.isBound()) {
return List.of();
}
IrisData data = null;
try {
data = IrisData.openRuntime(packFolder);
data = loadedPack == null ? IrisData.openRuntime(packFolder) : loadedPack;
if (!data.getContentGate().ready()) {
return List.of();
}
@@ -223,7 +238,7 @@ public final class PackValidator {
+ ": " + Objects.requireNonNullElse(e.getMessage(), "No failure detail."));
return List.of();
} finally {
if (data != null) {
if (data != null && data != loadedPack) {
try {
data.close();
} catch (Throwable closeFailure) {
@@ -168,6 +168,10 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
private transient volatile boolean generationPackFingerprintVerifiedByCaller;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
private transient volatile GenerationRegistryContract generationRegistryContract;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@@ -265,6 +269,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
dump();
clearLists();
generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
contentGate = null;
dimensionCustomBiomeResourceKeys.clear();
}
@@ -364,6 +369,23 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
}
}
/**
* Supplies the current-version fingerprint the caller already computed or verified for this data folder, so
* {@link #generationPackFingerprint()} does not hash the pack again.
*/
public synchronized void useVerifiedGenerationPackFingerprint(String fingerprint) {
String required = Objects.requireNonNull(fingerprint, "fingerprint");
if (generationPackFingerprint != null && !generationPackFingerprint.equals(required)) {
throw new IllegalStateException("Iris data already has a different generation pack fingerprint.");
}
generationPackFingerprint = required;
generationPackFingerprintVerifiedByCaller = true;
}
public boolean hasCallerVerifiedGenerationPackFingerprint() {
return generationPackFingerprintVerifiedByCaller;
}
public boolean hasGenerationRegistryContract() {
return generationRegistryContract != null;
}
@@ -750,6 +772,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
IrisObjectScale.invalidate(this);
contentGate = null;
generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
synchronized (dimensionCustomBiomeResourceKeys) {
dimensionCustomBiomeResourceKeys.clear();
}
@@ -85,7 +85,6 @@ import art.arcane.iris.generation.chunk.SectionBuffer;
import art.arcane.iris.generation.context.ChunkContext;
import art.arcane.iris.generation.context.IrisContext;
import art.arcane.volmlib.util.io.ReactiveFolder;
import art.arcane.volmlib.util.scheduling.ChronoLatch;
import art.arcane.iris.world.task.J;
import art.arcane.iris.world.runtime.WorldRuntimeControlService;
import art.arcane.volmlib.util.scheduling.Looper;
@@ -132,7 +131,7 @@ import java.util.function.BooleanSupplier;
@Data
public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChunkGenerator, Listener {
private static final int LOAD_LOCKS = Runtime.getRuntime().availableProcessors() * 4;
private static final long HOTLOAD_LOOP_DELAY_MS = 250L;
private static final long HOTLOAD_LOOP_DELAY_MS = 100L;
private static final long HOTLOAD_MAINTENANCE_DELAY_MS = 4000L;
private static final int PLAYER_ENTRY_MOVE_PADDING = 3;
private static final int SPAWN_HYDROLOGY_REACH = 256;
@@ -144,7 +143,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
private final ReactiveFolder folder;
private final ReentrantLock lock = new ReentrantLock();
private final KList<BlockPopulator> populators;
private final ChronoLatch hotloadChecker;
private final AtomicBoolean setup;
private final boolean studio;
private final AtomicBoolean studioEntryBootstrapActive;
@@ -187,7 +185,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
populators = new KList<>();
loadLock = new GenerationStageGate(LOAD_LOCKS, () -> closing);
this.world = world;
this.hotloadChecker = new ChronoLatch(1000, false);
this.studio = studio;
this.studioEntryBootstrapActive = new AtomicBoolean(studio);
this.dataLocation = dataLocation;
@@ -849,10 +846,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
return HOTLOAD_MAINTENANCE_DELAY_MS;
}
if (hotloadChecker.flip()) {
folder.check();
}
folder.check();
return HOTLOAD_LOOP_DELAY_MS;
}
@@ -52,6 +52,7 @@ import art.arcane.iris.world.runtime.WorldDeletionQueue;
import art.arcane.iris.studio.jigsaw.JigsawStudioActivation;
import art.arcane.iris.world.IrisToolbelt;
import art.arcane.volmlib.util.cache.AtomicCache;
import art.arcane.iris.world.history.EpochPolicy;
import art.arcane.iris.world.history.GenerationActivation;
import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.GenerationEpochContractFactory;
@@ -218,7 +219,17 @@ public class StudioSVC implements IrisService {
File dimensionRoot,
long worldSeed
) {
return publishGenerationHistory(sender, dimension, dimensionRoot, worldSeed, false);
return installIntoWorld(sender, dimension, dimensionRoot, worldSeed, EpochPolicy.configured());
}
public GenerationPublication installIntoWorld(
VolmitSender sender,
IrisDimension dimension,
File dimensionRoot,
long worldSeed,
EpochPolicy epochPolicy
) {
return publishGenerationHistory(sender, dimension, dimensionRoot, worldSeed, false, epochPolicy);
}
public IrisDimension replaceIntoWorld(
@@ -227,7 +238,8 @@ public class StudioSVC implements IrisService {
File dimensionRoot,
long worldSeed
) {
GenerationPublication publication = publishGenerationHistory(sender, dimension, dimensionRoot, worldSeed, true);
GenerationPublication publication = publishGenerationHistory(
sender, dimension, dimensionRoot, worldSeed, true, EpochPolicy.configured());
return publication == null ? null : publication.dimension();
}
@@ -248,7 +260,8 @@ public class StudioSVC implements IrisService {
IrisDimension dimension,
File dimensionRoot,
long worldSeed,
boolean stageUpdate
boolean stageUpdate,
EpochPolicy epochPolicy
) {
if (J.isPrimaryThread()) {
sender.sendMessage(IrisLanguage.text(
@@ -290,7 +303,8 @@ public class StudioSVC implements IrisService {
candidate.packFingerprint(),
worldSeed,
candidate.dimensionContract(),
candidate.registryContract()
candidate.registryContract(),
epochPolicy
);
}
Path installedPack = stageUpdate && history.pendingActivation().isPresent()
@@ -22,6 +22,7 @@ import art.arcane.volmlib.nativelib.NativeAdapters;
import art.arcane.volmlib.nativelib.server.NativeServerDiagnostics;
import art.arcane.iris.world.runtime.TransientWorldCleanupSupport;
import art.arcane.iris.world.runtime.WorldRuntimeControlService;
import art.arcane.iris.world.history.EpochPolicy;
import art.arcane.iris.world.history.GenerationHistory;
import com.google.common.util.concurrent.AtomicDouble;
import art.arcane.iris.spi.IrisLogging;
@@ -273,8 +274,9 @@ public class IrisCreator {
if (benchmark && !studio) {
installedDimension = studioService.installIntoTransientWorld(sender, resolvedDimension, dimensionRoot);
} else {
EpochPolicy epochPolicy = studio ? EpochPolicy.STUDIO : EpochPolicy.configured();
StudioSVC.GenerationPublication publication = studioService.installIntoWorld(
sender, resolvedDimension, dimensionRoot, seed);
sender, resolvedDimension, dimensionRoot, seed, epochPolicy);
installedDimension = publication == null ? null : publication.dimension();
if (publication != null) {
publishedHistory = publication.history();
@@ -0,0 +1,26 @@
package art.arcane.iris.world.history;
import art.arcane.iris.world.storage.Durability;
/**
* How a history publishes and re-checks its generation epochs. Relaxed and Studio histories skip the fsyncs of epoch
* packs, epoch metadata and the manifest, so a crash can lose or tear them. Studio epochs are also trusted after this process hashed them once, because Studio worlds
* are private to the server and discarded on restart.
*/
public enum EpochPolicy {
DURABLE,
RELAXED,
STUDIO;
public static EpochPolicy configured() {
return Durability.enabled() ? DURABLE : RELAXED;
}
public boolean syncs() {
return this == DURABLE;
}
public boolean trustsVerifiedPacks() {
return this == STUDIO;
}
}
@@ -64,8 +64,14 @@ public final class GenerationBoundaryStore {
private final Path dimensionRoot;
private final Path directory;
private final EpochPolicy policy;
public GenerationBoundaryStore(Path dimensionRoot) {
this(dimensionRoot, EpochPolicy.DURABLE);
}
public GenerationBoundaryStore(Path dimensionRoot, EpochPolicy policy) {
this.policy = Objects.requireNonNull(policy, "policy");
Path root = Objects.requireNonNull(dimensionRoot, "Dimension root").toAbsolutePath().normalize();
this.dimensionRoot = root;
this.directory = root.resolve("iris").resolve("generation").resolve("boundaries").normalize();
@@ -224,7 +230,7 @@ public final class GenerationBoundaryStore {
".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock"
)) {
ensureDirectory();
PublishedCatalog catalog = builder.publish(directory, activationId);
PublishedCatalog catalog = builder.publish(directory, activationId, policy);
Path target = snapshotPath(activationId);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
GenerationBoundary existing = load(activationId);
@@ -236,7 +242,7 @@ public final class GenerationBoundaryStore {
}
return existing;
}
publishAtomic(target, catalog.encoded(), "generation boundary catalog");
publishAtomic(target, catalog.encoded(), "generation boundary catalog", policy);
return load(activationId);
}
}
@@ -264,7 +270,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(directory);
}
private static Path ensureChildDirectory(Path parent, String name) throws IOException {
private Path ensureChildDirectory(Path parent, String name) throws IOException {
Path child = parent.resolve(name);
if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) {
requireSafeDirectory(child);
@@ -276,7 +282,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(child);
return child;
}
forceDirectory(parent);
forceDirectory(parent, policy);
return child;
}
@@ -357,7 +363,8 @@ public final class GenerationBoundaryStore {
return withChecksum(bodyBytes.toByteArray());
}
private static void publishAtomic(Path target, byte[] encoded, String kind) throws IOException {
private static void publishAtomic(Path target, byte[] encoded, String kind, EpochPolicy policy)
throws IOException {
Path directory = target.getParent();
Path temporary = Files.createTempFile(directory, ".boundary-", ".tmp");
try {
@@ -367,14 +374,16 @@ public final class GenerationBoundaryStore {
StandardOpenOption.TRUNCATE_EXISTING
)) {
writeFully(channel, ByteBuffer.wrap(encoded));
channel.force(true);
if (policy.syncs()) {
channel.force(true);
}
}
try {
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException error) {
throw new IOException("Generation boundary " + kind + " publication requires an atomic move", error);
}
forceDirectory(directory);
forceDirectory(directory, policy);
} finally {
Files.deleteIfExists(temporary);
}
@@ -483,8 +492,8 @@ public final class GenerationBoundaryStore {
}
}
private static void forceDirectory(Path path) throws IOException {
if (File.separatorChar == '\\') {
private static void forceDirectory(Path path, EpochPolicy policy) throws IOException {
if (!policy.syncs() || File.separatorChar == '\\') {
return;
}
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
@@ -521,7 +530,7 @@ public final class GenerationBoundaryStore {
}
}
private PublishedCatalog publish(Path directory, long activationId) throws IOException {
private PublishedCatalog publish(Path directory, long activationId, EpochPolicy policy) throws IOException {
if (masks.size() > MAX_REGION_COUNT) {
throw new IOException("Generation boundary exceeds the maximum region count");
}
@@ -529,7 +538,7 @@ public final class GenerationBoundaryStore {
sortRegionKeys(regionKeys);
Long2ObjectOpenHashMap<String> shardHashes = new Long2ObjectOpenHashMap<>(regionKeys.length);
for (long regionKey : regionKeys) {
String hash = MaskShard.publish(directory, masks.get(regionKey));
String hash = MaskShard.publish(directory, masks.get(regionKey), policy);
shardHashes.put(regionKey, hash);
}
byte[] identity = computeIdentity(activationId, chunkCount, regionKeys, shardHashes);
@@ -546,7 +555,7 @@ public final class GenerationBoundaryStore {
}
private static final class MaskShard {
private static String publish(Path directory, byte[] mask) throws IOException {
private static String publish(Path directory, byte[] mask, EpochPolicy policy) throws IOException {
byte[] encoded = encode(mask);
String hash = sha256(encoded);
Path target = directory.resolve(maskFileName(hash));
@@ -556,7 +565,7 @@ public final class GenerationBoundaryStore {
return hash;
}
try {
publishAtomic(target, encoded, "mask shard");
publishAtomic(target, encoded, "mask shard", policy);
} catch (FileAlreadyExistsException race) {
requireRegularFile(target, "Generation boundary mask");
read(target, hash);
@@ -69,7 +69,7 @@ public final class GenerationHistory {
this.store = Objects.requireNonNull(store, "store");
this.ownership = Objects.requireNonNull(ownership, "ownership");
this.kernels = Objects.requireNonNull(kernels, "kernels");
this.boundaries = new GenerationBoundaryStore(paths.dimensionRoot());
this.boundaries = new GenerationBoundaryStore(paths.dimensionRoot(), this.packs.policy());
this.terrainSignatures = new TerrainBoundarySignatureStore(paths.dimensionRoot());
this.semantics = GenerationSemanticIndex.loadRequired(paths.dimensionRoot(), unpublished);
this.savedBiomes = SavedBiomeStore.open(paths.dimensionRoot(), unpublished);
@@ -140,18 +140,33 @@ public final class GenerationHistory {
GenerationKernelRegistry kernels
) throws IOException {
return create(new FreshCreation(dimensionRoot, packSource, packFingerprint, worldSeed, dimensionContract, registryContract),
version, kernels, false);
version, kernels, false, EpochPolicy.configured());
}
public static GenerationHistory create(
Path dimensionRoot,
Path packSource,
String packFingerprint,
long worldSeed,
GenerationEpoch.DimensionContract dimensionContract,
GenerationRegistryContract registryContract,
EpochPolicy epochPolicy
) throws IOException {
GenerationKernelRegistry kernels = GenerationKernelRegistry.standard();
return create(new FreshCreation(dimensionRoot, packSource, packFingerprint, worldSeed, dimensionContract, registryContract),
kernels.current(), kernels, false, epochPolicy);
}
public static GenerationHistory createUnpublished(FreshCreation creation) throws IOException {
Objects.requireNonNull(creation, "creation");
Files.createDirectory(creation.dimensionRoot());
GenerationKernelRegistry kernels = GenerationKernelRegistry.standard();
return create(creation, kernels.current(), kernels, true);
return create(creation, kernels.current(), kernels, true, EpochPolicy.configured());
}
private static GenerationHistory create(FreshCreation creation, GenerationKernelRegistry.Version version,
GenerationKernelRegistry kernels, boolean unpublished) throws IOException {
GenerationKernelRegistry kernels, boolean unpublished,
EpochPolicy epochPolicy) throws IOException {
Path dimensionRoot = creation.dimensionRoot();
Path packSource = creation.packSource();
String packFingerprint = creation.packFingerprint();
@@ -180,16 +195,16 @@ public final class GenerationHistory {
kernels
);
requireSourceFingerprint(packSource, epoch.packFingerprint(), epoch.packFingerprintVersion());
GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot());
GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot(), epochPolicy);
Path publishedPack = packs.publish(
epoch.epochId(),
epoch.packFingerprint(),
epoch.packFingerprintVersion(),
packSource
);
forceEpochPublication(paths, epoch.epochId());
forceEpochPublication(paths, epoch.epochId(), epochPolicy);
GenerationSemanticIndex.initialize(paths.dimensionRoot());
GenerationHistoryStore store = GenerationHistoryStore.initialize(paths.generationRoot(), epoch);
GenerationHistoryStore store = GenerationHistoryStore.initialize(paths.generationRoot(), epoch, epochPolicy);
return new GenerationHistory(paths, packs, store, ownership, kernels,
Optional.of(new FreshPublication(publishedPack, epoch)), unpublished);
}
@@ -315,7 +330,7 @@ public final class GenerationHistory {
expectedEpoch.packFingerprint(),
expectedEpoch.packFingerprintVersion()
);
forceEpochPublication(paths, expectedEpoch.epochId());
forceEpochPublication(paths, expectedEpoch.epochId(), history.packs.policy());
}
migrateLegacyMantle(paths, history.activeActivation().activationId());
if (!legacyExists) {
@@ -370,6 +385,75 @@ public final class GenerationHistory {
GenerationRegistryContract registryContract,
int transitionWidthBlocks,
GenerationKernelRegistry.Version version
) throws IOException {
GenerationEpoch candidate = stageableCandidate(
packFingerprint, packFingerprintVersion, dimensionContract, registryContract, version);
Optional<GenerationActivation> pending = pendingActivationFor(candidate);
if (pending.isPresent()) {
return pending.get();
}
requireSourceFingerprint(
packSource,
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
if (store.activeEpoch().equals(candidate)) {
return requireActiveCandidate(candidate);
}
packs.publish(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion(),
packSource,
activePackLinkBasis().orElse(null)
);
return preparePublishedCandidate(candidate, transitionWidthBlocks);
}
/**
* Stages a pack tree this process already hashed. Unsynced histories move it into the epoch repository, so
* neither the tree nor the published pack is hashed again; durable ones still copy, sync and re-hash it. The
* tree must not be modified after it was hashed.
*/
public synchronized GenerationActivation stageVerifiedUpdate(
VerifiedPackTree pack,
GenerationEpoch.DimensionContract dimensionContract,
GenerationRegistryContract registryContract,
int transitionWidthBlocks
) throws IOException {
GenerationEpoch candidate = stageableCandidate(
pack.fingerprint(), pack.fingerprintVersion(), dimensionContract, registryContract, kernels.current());
Optional<GenerationActivation> pending = pendingActivationFor(candidate);
if (pending.isPresent()) {
return pending.get();
}
if (store.activeEpoch().equals(candidate)) {
return requireActiveCandidate(candidate);
}
publishVerifiedPack(candidate, pack);
return preparePublishedCandidate(candidate, transitionWidthBlocks);
}
private void publishVerifiedPack(GenerationEpoch candidate, VerifiedPackTree pack) throws IOException {
if (!packs.policy().syncs()) {
packs.adopt(candidate.epochId(), pack);
return;
}
packs.publish(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion(),
pack.root(),
activePackLinkBasis().orElse(null)
);
}
private GenerationEpoch stageableCandidate(
String packFingerprint,
int packFingerprintVersion,
GenerationEpoch.DimensionContract dimensionContract,
GenerationRegistryContract registryContract,
GenerationKernelRegistry.Version version
) throws IOException {
GenerationEpoch candidate = epoch(
packFingerprint,
@@ -391,50 +475,54 @@ public final class GenerationHistory {
if (!store.activeEpoch().dimensionContract().hasSameLayout(candidate.dimensionContract())) {
throw new IllegalArgumentException("Generation update changes the immutable dimension contract.");
}
return candidate;
}
private Optional<GenerationActivation> pendingActivationFor(GenerationEpoch candidate) throws IOException {
Optional<GenerationActivation> pending = store.pendingActivation();
if (pending.isPresent()) {
GenerationActivation activation = pending.get();
if (!activation.epochId().equals(candidate.epochId())) {
throw new IllegalStateException("A different generation activation is already pending.");
}
packs.requireExactPack(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
return activation;
if (pending.isEmpty()) {
return Optional.empty();
}
if (store.activeEpoch().equals(candidate)) {
requireSourceFingerprint(
packSource,
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
packs.requireExactPack(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
return store.activeActivation();
if (!pending.get().epochId().equals(candidate.epochId())) {
throw new IllegalStateException("A different generation activation is already pending.");
}
requireSourceFingerprint(
packSource,
packs.requireExactPack(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
packs.publish(
return pending;
}
private GenerationActivation requireActiveCandidate(GenerationEpoch candidate) throws IOException {
packs.requireExactPack(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion(),
packSource
candidate.packFingerprintVersion()
);
forceEpochPublication(paths, candidate.epochId());
return store.activeActivation();
}
private GenerationActivation preparePublishedCandidate(
GenerationEpoch candidate,
int transitionWidthBlocks
) throws IOException {
forceEpochPublication(paths, candidate.epochId(), packs.policy());
return store.preparePendingActivation(candidate, transitionWidthBlocks);
}
/**
* The active epoch's published pack, which new packs hard-link unchanged files against. Empty when it is
* missing or unsafe, in which case every file is copied.
*/
public Optional<Path> activePackLinkBasis() {
try {
return Optional.of(packs.requireSafePackRoot(store.activeEpoch().epochId()));
} catch (IOException missingOrUnsafe) {
return Optional.empty();
}
}
GenerationActivation promotePending(
Collection<TerrainBoundarySignature> signatures
) throws IOException {
@@ -1331,20 +1419,20 @@ public final class GenerationHistory {
private static void forceEpochPublication(
GenerationHistoryPaths paths,
String epochId
String epochId,
EpochPolicy epochPolicy
) throws IOException {
Path epochRoot = paths.epochRoot(epochId);
if (!Files.isDirectory(epochRoot, LinkOption.NOFOLLOW_LINKS)
|| Files.isSymbolicLink(epochRoot)) {
throw new IOException("Generation epoch is not a safe directory: " + epochRoot);
}
if (File.separatorChar != '\\') {
if (Durability.enabled()) {
GenerationPackRepository.forceDirectoryTree(epochRoot, GenerationHistory::forceDirectory);
}
forceDirectory(paths.epochsRoot());
forceDirectory(paths.generationRoot());
if (!epochPolicy.syncs() || File.separatorChar == '\\') {
return;
}
GenerationPackRepository.forceDirectoryTree(epochRoot, GenerationHistory::forceDirectory);
forceDirectory(paths.epochsRoot());
forceDirectory(paths.generationRoot());
}
private static void forceDirectory(Path directory) throws IOException {
@@ -1395,6 +1395,9 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable {
Path packRoot = history.packRoot(activation.activationId());
IrisData data = IrisData.openRuntime(packRoot.toFile());
try {
if (epoch.packFingerprintVersion() == GenerationPackFingerprint.CURRENT_VERSION) {
data.useVerifiedGenerationPackFingerprint(epoch.packFingerprint());
}
data.bindGenerationRegistryContract(epoch.registryContract());
IrisDimension dimension = data.getDimensionLoader().load(epoch.dimensionContract().dimensionKey());
if (dimension == null) {
@@ -48,7 +48,11 @@ public final class GenerationHistoryStore {
private final Path generationDirectory;
private final Path manifestPath;
private final Clock clock;
private static final DirectorySync NO_DIRECTORY_SYNC = directory -> {
};
private final DirectorySync directorySync;
private final EpochPolicy policy;
private GenerationManifest manifest;
private IOException failure;
@@ -56,20 +60,34 @@ public final class GenerationHistoryStore {
Path generationDirectory,
GenerationManifest manifest,
Clock clock,
DirectorySync directorySync
DirectorySync directorySync,
EpochPolicy policy
) {
this.generationDirectory = generationDirectory;
this.manifestPath = generationDirectory.resolve(MANIFEST_FILE_NAME);
this.manifest = Objects.requireNonNull(manifest, "manifest");
this.clock = Objects.requireNonNull(clock, "clock");
this.directorySync = Objects.requireNonNull(directorySync, "directorySync");
this.policy = Objects.requireNonNull(policy, "policy");
}
public static GenerationHistoryStore initialize(
Path generationDirectory,
GenerationEpoch initialEpoch
) throws IOException {
return initialize(generationDirectory, initialEpoch, Clock.systemUTC());
return initialize(generationDirectory, initialEpoch, EpochPolicy.configured());
}
/**
* Histories whose policy does not sync skip every manifest and epoch metadata fsync, so a crash can lose the
* latest manifest update.
*/
public static GenerationHistoryStore initialize(
Path generationDirectory,
GenerationEpoch initialEpoch,
EpochPolicy policy
) throws IOException {
return initialize(generationDirectory, initialEpoch, Clock.systemUTC(), manifestDirectorySync(policy), policy);
}
static GenerationHistoryStore initialize(
@@ -85,6 +103,16 @@ public final class GenerationHistoryStore {
GenerationEpoch initialEpoch,
Clock clock,
DirectorySync directorySync
) throws IOException {
return initialize(generationDirectory, initialEpoch, clock, directorySync, EpochPolicy.configured());
}
private static GenerationHistoryStore initialize(
Path generationDirectory,
GenerationEpoch initialEpoch,
Clock clock,
DirectorySync directorySync,
EpochPolicy policy
) throws IOException {
Path directory = normalizeDirectory(generationDirectory);
requireSafeParent(directory);
@@ -92,7 +120,7 @@ public final class GenerationHistoryStore {
String lockName = "." + Objects.requireNonNull(directory.getFileName(), "Generation history directory name")
+ ".manifest.lock";
try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire(parent, lockName)) {
ensureDirectory(directory);
ensureDirectory(directory, policy);
Path manifestPath = directory.resolve(MANIFEST_FILE_NAME);
if (Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
throw new FileAlreadyExistsException(manifestPath.toString());
@@ -103,16 +131,25 @@ public final class GenerationHistoryStore {
requiredClock.millis()
);
DirectorySync requiredDirectorySync = Objects.requireNonNull(directorySync, "directorySync");
writeManifestAtomically(directory, manifestPath, manifest, null, false, requiredDirectorySync);
return new GenerationHistoryStore(directory, manifest, requiredClock, requiredDirectorySync);
writeManifestAtomically(directory, manifestPath, manifest, null, false, requiredDirectorySync, policy);
return new GenerationHistoryStore(directory, manifest, requiredClock, requiredDirectorySync, policy);
}
}
public static GenerationHistoryStore open(Path generationDirectory) throws IOException {
return open(generationDirectory, Clock.systemUTC());
return open(generationDirectory, EpochPolicy.configured());
}
public static GenerationHistoryStore open(Path generationDirectory, EpochPolicy policy) throws IOException {
return open(generationDirectory, Clock.systemUTC(), policy);
}
static GenerationHistoryStore open(Path generationDirectory, Clock clock) throws IOException {
return open(generationDirectory, clock, EpochPolicy.configured());
}
private static GenerationHistoryStore open(Path generationDirectory, Clock clock, EpochPolicy policy)
throws IOException {
Path directory = normalizeDirectory(generationDirectory);
requireDirectory(directory);
Path manifestPath = directory.resolve(MANIFEST_FILE_NAME);
@@ -122,10 +159,15 @@ public final class GenerationHistoryStore {
directory,
manifest,
clock,
GenerationHistoryStore::forceDirectory
manifestDirectorySync(policy),
policy
);
}
private static DirectorySync manifestDirectorySync(EpochPolicy policy) {
return policy.syncs() ? GenerationHistoryStore::forceDirectory : NO_DIRECTORY_SYNC;
}
public Path generationDirectory() {
return generationDirectory;
}
@@ -213,7 +255,7 @@ public final class GenerationHistoryStore {
private void writeUpdatedManifest(GenerationManifest updated) throws IOException {
try {
writeManifestAtomically(generationDirectory, manifestPath, updated, manifest, true, directorySync);
writeManifestAtomically(generationDirectory, manifestPath, updated, manifest, true, directorySync, policy);
} catch (IOException error) {
reconcileAfterWriteFailure(error);
throw error;
@@ -261,7 +303,8 @@ public final class GenerationHistoryStore {
GenerationManifest manifest,
GenerationManifest previous,
boolean replaceExisting,
DirectorySync directorySync
DirectorySync directorySync,
EpochPolicy policy
) throws IOException {
requireSafeParent(generationDirectory);
requireDirectory(generationDirectory);
@@ -271,7 +314,7 @@ public final class GenerationHistoryStore {
}
for (GenerationEpoch epoch : manifest.epochs()) {
if (previous == null || previous.epoch(epoch.epochId()).isEmpty()) {
publishEpoch(generationDirectory, epoch);
publishEpoch(generationDirectory, epoch, policy);
}
}
Path temporary = Files.createTempFile(generationDirectory, ".manifest-", ".tmp");
@@ -285,7 +328,7 @@ public final class GenerationHistoryStore {
while (buffer.hasRemaining()) {
channel.write(buffer);
}
Durability.force(channel);
forceFile(channel, policy);
}
try {
if (replaceExisting) {
@@ -332,11 +375,12 @@ public final class GenerationHistoryStore {
}
}
private static void publishEpoch(Path generationDirectory, GenerationEpoch epoch) throws IOException {
private static void publishEpoch(Path generationDirectory, GenerationEpoch epoch, EpochPolicy policy)
throws IOException {
Path epochsDirectory = generationDirectory.resolve("epochs");
ensureDirectory(epochsDirectory);
ensureDirectory(epochsDirectory, policy);
Path epochDirectory = epochDirectory(generationDirectory, epoch.epochId());
ensureDirectory(epochDirectory);
ensureDirectory(epochDirectory, policy);
Path metadata = epochDirectory.resolve("epoch.json");
if (Files.exists(metadata, LinkOption.NOFOLLOW_LINKS)) {
if (!readEpoch(generationDirectory, epoch.epochId()).equals(epoch)) {
@@ -355,14 +399,14 @@ public final class GenerationHistoryStore {
while (buffer.hasRemaining()) {
channel.write(buffer);
}
Durability.force(channel);
forceFile(channel, policy);
}
try {
Files.move(temporary, metadata, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException exception) {
throw new IOException("Generation history requires atomic epoch publication.", exception);
}
forceDirectory(epochDirectory);
forceDirectory(epochDirectory, policy);
} finally {
Files.deleteIfExists(temporary);
}
@@ -379,24 +423,37 @@ public final class GenerationHistoryStore {
return Objects.requireNonNull(directory, "generationDirectory").toAbsolutePath().normalize();
}
private static void ensureDirectory(Path directory) throws IOException {
private static void ensureDirectory(Path directory, EpochPolicy policy) throws IOException {
requireSafeParent(directory);
Path parent = Objects.requireNonNull(directory.getParent(), "Generation history parent");
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
requireDirectory(directory);
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent"));
forceDirectory(parent, policy);
return;
}
try {
Files.createDirectory(directory);
} catch (FileAlreadyExistsException race) {
requireDirectory(directory);
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent"));
forceDirectory(parent, policy);
return;
}
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent"));
forceDirectory(parent, policy);
requireDirectory(directory);
}
private static void forceFile(FileChannel channel, EpochPolicy policy) throws IOException {
if (policy.syncs()) {
Durability.force(channel);
}
}
private static void forceDirectory(Path directory, EpochPolicy policy) throws IOException {
if (policy.syncs()) {
forceDirectory(directory);
}
}
private static void requireDirectory(Path directory) throws IOException {
requireSafeParent(directory);
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
@@ -19,11 +19,15 @@ import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
@@ -39,14 +43,25 @@ public final class GenerationPackRepository {
private final Path dimensionRoot;
private final Path generationRoot;
private final Path epochsRoot;
private final EpochPolicy policy;
private final Set<String> verifiedPacks = ConcurrentHashMap.newKeySet();
public GenerationPackRepository(Path dimensionRoot) {
this(dimensionRoot, EpochPolicy.configured());
}
public GenerationPackRepository(Path dimensionRoot, EpochPolicy policy) {
Path root = Objects.requireNonNull(dimensionRoot, "dimensionRoot")
.toAbsolutePath()
.normalize();
this.dimensionRoot = root;
generationRoot = root.resolve("iris").resolve("generation");
epochsRoot = generationRoot.resolve("epochs");
this.policy = Objects.requireNonNull(policy, "policy");
}
public EpochPolicy policy() {
return policy;
}
public Path generationRoot() {
@@ -61,11 +76,26 @@ public final class GenerationPackRepository {
return epochRoot(epochId).resolve("pack");
}
public synchronized Path publish(
public Path publish(
String epochId,
String packFingerprint,
int packFingerprintVersion,
Path source
) throws IOException {
return publish(epochId, packFingerprint, packFingerprintVersion, source, null);
}
/**
* Files identical to the published {@code basisPack} are hard-linked instead of copied. Published packs are
* immutable and were already synced, so only new or changed files pay for a copy and an fsync. Unsynced
* repositories skip every fsync.
*/
public synchronized Path publish(
String epochId,
String packFingerprint,
int packFingerprintVersion,
Path source,
Path basisPack
) throws IOException {
String requiredEpochId = requireDigest(epochId, "epochId");
String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
@@ -75,7 +105,7 @@ public final class GenerationPackRepository {
".epoch-" + requiredEpochId + ".lock"
)) {
ensureEpochsRoot();
return publishLocked(requiredEpochId, requiredFingerprint, packFingerprintVersion, source);
return publishLocked(requiredEpochId, requiredFingerprint, packFingerprintVersion, source, basisPack);
}
}
@@ -83,7 +113,8 @@ public final class GenerationPackRepository {
String epochId,
String packFingerprint,
int packFingerprintVersion,
Path source
Path source,
Path basisPack
) throws IOException {
Path epochDirectory = ensureChildDirectory(epochsRoot, epochId);
Path target = epochDirectory.resolve("pack");
@@ -94,39 +125,102 @@ public final class GenerationPackRepository {
Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
try {
Files.delete(stage);
copyPackTree(source, stage);
copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), publicationCopyMode(), basisPack, null);
requireFingerprint(stage, packFingerprint, packFingerprintVersion);
try (AtomicDirectoryPublisher.Publication publication =
AtomicDirectoryPublisher.publishAbsent(stage, target)) {
publication.commit();
} catch (FileAlreadyExistsException race) {
return requireExactPack(epochId, packFingerprint, packFingerprintVersion);
}
forceDirectory(epochDirectory);
validateExistingAncestors(epochId);
requireSafeDirectory(target, "Generation epoch pack is missing or unsafe");
return target;
return commitStage(epochId, stage, packFingerprint, packFingerprintVersion);
} finally {
if (Files.exists(stage, LinkOption.NOFOLLOW_LINKS)) {
AtomicDirectoryPublisher.deleteTree(stage);
}
deleteLeftoverStage(stage);
}
}
/**
* Publishes a tree this process already hashed by moving it into place instead of copying and hashing it again.
* The tree must be on the repository's filesystem and is consumed. Its files were never synced, so only
* repositories that skip fsyncs may adopt one.
*/
public synchronized Path adopt(String epochId, VerifiedPackTree pack) throws IOException {
if (policy.syncs()) {
throw new IllegalStateException("Durable generation epochs cannot adopt an unsynced pack tree.");
}
String requiredEpochId = requireDigest(epochId, "epochId");
requireDigest(pack.fingerprint(), "packFingerprint");
ensureEpochsRoot();
try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire(
epochsRoot,
".epoch-" + requiredEpochId + ".lock"
)) {
ensureEpochsRoot();
return adoptLocked(requiredEpochId, pack);
}
}
private Path adoptLocked(String epochId, VerifiedPackTree pack) throws IOException {
Path epochDirectory = ensureChildDirectory(epochsRoot, epochId);
if (Files.exists(epochDirectory.resolve("pack"), LinkOption.NOFOLLOW_LINKS)) {
return requireExactPack(epochId, pack.fingerprint(), pack.fingerprintVersion());
}
Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
try {
Files.delete(stage);
Files.move(pack.root(), stage, StandardCopyOption.ATOMIC_MOVE);
return commitStage(epochId, stage, pack.fingerprint(), pack.fingerprintVersion());
} finally {
deleteLeftoverStage(stage);
}
}
private Path commitStage(String epochId, Path stage, String packFingerprint, int packFingerprintVersion)
throws IOException {
Path epochDirectory = stage.getParent();
Path target = epochDirectory.resolve("pack");
try (AtomicDirectoryPublisher.Publication publication =
AtomicDirectoryPublisher.publishAbsent(stage, target)) {
publication.commit();
} catch (FileAlreadyExistsException race) {
return requireExactPack(epochId, packFingerprint, packFingerprintVersion);
}
syncDirectory(epochDirectory);
validateExistingAncestors(epochId);
requireSafeDirectory(target, "Generation epoch pack is missing or unsafe");
rememberVerifiedPack(epochId, packFingerprint, packFingerprintVersion);
return target;
}
private static void deleteLeftoverStage(Path stage) throws IOException {
if (Files.exists(stage, LinkOption.NOFOLLOW_LINKS)) {
AtomicDirectoryPublisher.deleteTree(stage);
}
}
/**
* Hashes the published pack unless this repository trusts packs it verified itself and already did so.
*/
public Path requireExactPack(
String epochId,
String packFingerprint,
int packFingerprintVersion
) throws IOException {
Path pack = requireSafePackRoot(epochId);
requireFingerprint(
pack,
requireDigest(packFingerprint, "packFingerprint"),
packFingerprintVersion
);
String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
if (policy.trustsVerifiedPacks()
&& verifiedPacks.contains(verifiedPackKey(epochId, requiredFingerprint, packFingerprintVersion))) {
return pack;
}
requireFingerprint(pack, requiredFingerprint, packFingerprintVersion);
rememberVerifiedPack(epochId, requiredFingerprint, packFingerprintVersion);
return pack;
}
private void rememberVerifiedPack(String epochId, String packFingerprint, int packFingerprintVersion) {
if (policy.trustsVerifiedPacks()) {
verifiedPacks.add(verifiedPackKey(epochId, packFingerprint, packFingerprintVersion));
}
}
private static String verifiedPackKey(String epochId, String packFingerprint, int packFingerprintVersion) {
return epochId + '/' + packFingerprintVersion + '/' + packFingerprint;
}
Path requireSafePackRoot(String epochId) throws IOException {
String requiredEpochId = requireDigest(epochId, "epochId");
validateExistingAncestors(requiredEpochId);
@@ -157,21 +251,25 @@ public final class GenerationPackRepository {
requireSafeDirectory(epoch, "Generation epoch path is not a safe directory");
}
private static Path ensureChildDirectory(Path parent, String name) throws IOException {
private PackCopyMode publicationCopyMode() {
return policy.syncs() ? PackCopyMode.DURABLE : PackCopyMode.SCRATCH;
}
private Path ensureChildDirectory(Path parent, String name) throws IOException {
Path child = parent.resolve(name);
if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) {
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
forceDirectory(parent);
syncDirectory(parent);
return child;
}
try {
Files.createDirectory(child);
} catch (FileAlreadyExistsException race) {
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
forceDirectory(parent);
syncDirectory(parent);
return child;
}
forceDirectory(parent);
syncDirectory(parent);
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
return child;
}
@@ -190,8 +288,8 @@ public final class GenerationPackRepository {
}
}
private static void forceDirectory(Path directory) throws IOException {
if (File.separatorChar == '\\') {
private void syncDirectory(Path directory) throws IOException {
if (!policy.syncs() || File.separatorChar == '\\') {
return;
}
try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) {
@@ -202,24 +300,36 @@ public final class GenerationPackRepository {
}
public static void copyPackTree(Path source, Path target) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool();
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
copyPackTree(source, target, executor, workers);
copyPackTree(source, target, defaultExecutor(), defaultWorkers());
}
/**
* Copies a pack without syncing it, for scratch copies that are not published as they are. Files identical to
* the optional {@code basisPack} are hard-linked to it, so the copy must be treated as read-only.
*
* @param basisSourceState the state the source had when {@code basisPack} was copied from it, or null. With it,
* a file whose size and modification time still match is linked without reading either
* copy; without it, files are compared by content
*/
public static void snapshotPackTree(Path source, Path target, Path basisPack, PackTreeState basisSourceState)
throws IOException {
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, basisPack,
basisSourceState);
}
static void copyPackTree(Path source, Path target, Executor executor, int workers) throws IOException {
copyPackTree(source, target, executor, workers, PackCopyMode.DURABLE, null, null);
}
static void copyPackTree(
Path source, Path target, Executor executor, int workers, PackCopyMode mode, Path basisPack,
PackTreeState basisSourceState
) throws IOException {
Objects.requireNonNull(executor, "executor");
if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) {
throw new IllegalArgumentException("Pack copy workers must be between 1 and " + MAXIMUM_COPY_WORKERS + ".");
}
Path sourcePath = Objects.requireNonNull(source, "source").toAbsolutePath().normalize();
if (Files.isSymbolicLink(sourcePath)) {
throw new IOException("Pack source is a symbolic link: " + sourcePath);
}
Path normalizedSource = sourcePath.toRealPath();
if (!Files.isDirectory(normalizedSource, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Pack source is not a directory: " + normalizedSource);
}
Path normalizedSource = requirePackSource(source);
Path normalizedTarget = Objects.requireNonNull(target, "target").toAbsolutePath().normalize();
if (Files.exists(normalizedTarget, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(normalizedTarget)) {
throw new IOException("Pack publication stage already exists: " + normalizedTarget);
@@ -229,7 +339,45 @@ public final class GenerationPackRepository {
+ normalizedSource + " and " + normalizedTarget);
}
List<Path> sourceFiles = new ArrayList<>();
PackTreeState sourceState = walkPackTree(normalizedSource, directory ->
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory)));
List<Path> sourceFiles = sourceState.files().keySet().stream().map(normalizedSource::resolve).toList();
Path basis = basisPack == null ? null : basisPack.toAbsolutePath().normalize();
UnchangedFile unchanged = basisSourceState == null
? GenerationPackRepository::hasSameContent
: (relative, sourceFile, basisFile) -> basisSourceState.stamp(relative).equals(sourceState.stamp(relative));
Set<Path> unsyncedCopies = ConcurrentHashMap.newKeySet();
executeFilePhase(sourceFiles, executor, workers, sourceFile -> {
Path destination = copyDestination(normalizedSource, normalizedTarget, sourceFile);
if (basis != null && linkUnchangedFile(
normalizedSource.relativize(sourceFile), sourceFile, basis, destination, unchanged)) {
return;
}
Files.copy(sourceFile, destination, StandardCopyOption.COPY_ATTRIBUTES);
unsyncedCopies.add(destination);
});
if (mode == PackCopyMode.DURABLE) {
executeFilePhase(List.copyOf(unsyncedCopies), executor, workers, GenerationPackRepository::forceFile);
}
}
static Path requirePackSource(Path source) throws IOException {
Path sourcePath = Objects.requireNonNull(source, "source").toAbsolutePath().normalize();
if (Files.isSymbolicLink(sourcePath)) {
throw new IOException("Pack source is a symbolic link: " + sourcePath);
}
Path normalizedSource = sourcePath.toRealPath();
if (!Files.isDirectory(normalizedSource, LinkOption.NOFOLLOW_LINKS)) {
throw new IOException("Pack source is not a directory: " + normalizedSource);
}
return normalizedSource;
}
/**
* Visits every directory and lists every file a pack copy includes, rejecting links and special files.
*/
static PackTreeState walkPackTree(Path normalizedSource, FileAction includedDirectory) throws IOException {
Map<Path, PackTreeState.FileStamp> files = new LinkedHashMap<>();
Files.walkFileTree(normalizedSource, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
@@ -241,7 +389,7 @@ public final class GenerationPackRepository {
&& PackDirectoryResolver.isHiddenName(directory.getFileName().toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory));
includedDirectory.run(directory);
return FileVisitResult.CONTINUE;
}
@@ -259,7 +407,7 @@ public final class GenerationPackRepository {
|| fileName.endsWith(".code-workspace")) {
return FileVisitResult.CONTINUE;
}
sourceFiles.add(file);
files.put(relative, new PackTreeState.FileStamp(attributes.size(), attributes.lastModifiedTime()));
return FileVisitResult.CONTINUE;
}
@@ -268,17 +416,42 @@ public final class GenerationPackRepository {
throw new IOException("Unable to copy pack entry: " + file, failure);
}
});
executeFilePhase(sourceFiles, executor, workers, sourceFile ->
Files.copy(sourceFile, copyDestination(normalizedSource, normalizedTarget, sourceFile),
StandardCopyOption.COPY_ATTRIBUTES));
executeFilePhase(sourceFiles, executor, workers, sourceFile ->
forceFile(copyDestination(normalizedSource, normalizedTarget, sourceFile)));
return new PackTreeState(files);
}
private static boolean linkUnchangedFile(
Path relative, Path sourceFile, Path basis, Path destination, UnchangedFile unchanged
) {
Path basisFile = basis.resolve(relative).normalize();
if (!basisFile.startsWith(basis)) {
return false;
}
try {
if (!Files.isRegularFile(basisFile, LinkOption.NOFOLLOW_LINKS)
|| !unchanged.test(relative, sourceFile, basisFile)) {
return false;
}
Files.createLink(destination, basisFile);
return true;
} catch (IOException | UnsupportedOperationException | SecurityException unsupported) {
return false;
}
}
private static boolean hasSameContent(Path relative, Path sourceFile, Path basisFile) throws IOException {
return Files.mismatch(basisFile, sourceFile) == -1L;
}
private static Executor defaultExecutor() {
return IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool();
}
private static int defaultWorkers() {
return Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
}
static void forceDirectoryTree(Path root, FileAction force) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool();
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
forceDirectoryTree(root, executor, workers, force);
forceDirectoryTree(root, defaultExecutor(), defaultWorkers(), force);
}
static void forceDirectoryTree(Path root, Executor executor, int workers, FileAction force) throws IOException {
@@ -396,11 +569,21 @@ public final class GenerationPackRepository {
return requiredValue;
}
enum PackCopyMode {
DURABLE,
SCRATCH
}
@FunctionalInterface
interface FileAction {
void run(Path file) throws IOException;
}
@FunctionalInterface
private interface UnchangedFile {
boolean test(Path relative, Path sourceFile, Path basisFile) throws IOException;
}
private record FileWork(List<Path> files, FileAction action, AtomicInteger next, AtomicBoolean failed) {
}
@@ -261,19 +261,25 @@ public final class GenerationRegistryContractFactory {
ReferencedPlatformKeys referenced = referencedPlatformKeys(packRoot, requiredRegistries);
addPlatformDefinitions(definitions, BLOCK_REGISTRY, referenced.blockKeys(), requiredGenerationRegistry);
addPlatformDefinitions(definitions, ENTITY_TYPE_REGISTRY, referenced.entityKeys(), requiredGenerationRegistry);
GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry)
.withBiomeTags(biomeTags)
GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry).withBiomeTags(biomeTags)
.withCustomBiomeStandIns(customBiomeStandIns);
String actualPackFingerprint = GenerationPackFingerprint.compute(
packRoot,
GenerationPackFingerprint.CURRENT_VERSION
);
if (!requiredPackFingerprint.equals(actualPackFingerprint)) {
if (!requiredPackFingerprint.equals(packFingerprintAfterCapture(requiredData, packRoot))) {
throw new IOException("Iris generation registry capture rejected a changed pack.");
}
return captured;
}
/**
* A pack whose fingerprint the caller verified is immutable for the lifetime of its data, so it is not hashed
* again to detect edits made during the capture.
*/
private static String packFingerprintAfterCapture(IrisData data, Path packRoot) throws IOException {
if (data.hasCallerVerifiedGenerationPackFingerprint()) {
return data.generationPackFingerprint();
}
return GenerationPackFingerprint.compute(packRoot, GenerationPackFingerprint.CURRENT_VERSION);
}
public static CustomBiomeDefinition customBiomeDefinition(
IrisData data,
IrisDimension dimension,
@@ -0,0 +1,48 @@
package art.arcane.iris.world.history;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* The size and modification time of every file a pack copy would include, keyed by path relative to the pack root.
* Two equal states mean no included file was added, removed or rewritten in between, unless a writer preserved
* both size and modification time.
*/
public final class PackTreeState {
private final Map<Path, FileStamp> files;
PackTreeState(Map<Path, FileStamp> files) {
this.files = Collections.unmodifiableMap(new LinkedHashMap<>(files));
}
public static PackTreeState capture(Path packRoot) throws IOException {
return GenerationPackRepository.walkPackTree(GenerationPackRepository.requirePackSource(packRoot), directory -> {
});
}
Map<Path, FileStamp> files() {
return files;
}
Optional<FileStamp> stamp(Path relative) {
return Optional.ofNullable(files.get(relative));
}
@Override
public boolean equals(Object other) {
return other instanceof PackTreeState state && files.equals(state.files);
}
@Override
public int hashCode() {
return files.hashCode();
}
record FileStamp(long sizeBytes, FileTime modified) {
}
}
@@ -0,0 +1,39 @@
package art.arcane.iris.world.history;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Objects;
/**
* A pack tree together with the fingerprint this process computed from it. Only {@link #hash(Path)} creates one,
* so a holder can hand the tree to the epoch repository without it being hashed again.
*/
public final class VerifiedPackTree {
private final Path root;
private final String fingerprint;
private final int fingerprintVersion;
private VerifiedPackTree(Path root, String fingerprint, int fingerprintVersion) {
this.root = root;
this.fingerprint = fingerprint;
this.fingerprintVersion = fingerprintVersion;
}
public static VerifiedPackTree hash(Path root) throws IOException {
Path normalizedRoot = Objects.requireNonNull(root, "root").toAbsolutePath().normalize();
int version = GenerationPackFingerprint.CURRENT_VERSION;
return new VerifiedPackTree(normalizedRoot, GenerationPackFingerprint.compute(normalizedRoot, version), version);
}
public Path root() {
return root;
}
public String fingerprint() {
return fingerprint;
}
public int fingerprintVersion() {
return fingerprintVersion;
}
}
@@ -50,6 +50,7 @@
# {befb} Formatierter Teil einer Engine-Zeitmessungsbezeichnung vor dem Klammerteil.
# {before} Wert vor der Änderung oder unerreichbare Baumblöcke vor der Reparatur.
# {biome} Name oder Kennung des angezeigten Bioms.
# {biomes} Biome, deren Änderungen erst nach einem Serverneustart gelten.
# {block} Typ oder Beschreibung des untersuchten Blocks.
# {blockX} X-Koordinate des Blocks oder Teleportationsziels.
# {blockY} Y-Koordinate des Blocks oder Teleportationsziels.
@@ -50,6 +50,7 @@
# {befb} Parte con formato de una etiqueta de tiempos del motor situada antes del fragmento entre corchetes.
# {before} Valor anterior al cambio o bloques del árbol inaccesibles antes de repararlo.
# {biome} Nombre o identificador del bioma mostrado.
# {biomes} Biomas cuyos cambios solo se aplican tras reiniciar el servidor.
# {block} Tipo o descripción del bloque inspeccionado.
# {blockX} Coordenada X del bloque o del destino de teletransporte.
# {blockY} Coordenada Y del bloque o del destino de teletransporte.
@@ -55,6 +55,7 @@
# {befb} Moottorin ajoitusotsikon muotoiltu osa ennen hakasulkuosaa.
# {before} Arvo ennen muutosta tai saavuttamattomat puulohkot ennen korjausta.
# {biome} Näytettävän biomin nimi tai tunniste.
# {biomes} Biomit, joiden muutokset tulevat voimaan vasta palvelimen uudelleenkäynnistyksen jälkeen.
# {block} Tarkasteltavan lohkon tyyppi tai kuvaus.
# {blockX} Lohkon tai teleporttikohteen X-koordinaatti.
# {blockY} Lohkon tai teleporttikohteen Y-koordinaatti.
@@ -50,6 +50,7 @@
# {befb} Partie mise en forme d’un libellé de mesure du moteur, avant le passage entre crochets.
# {before} Valeur avant modification ou blocs d’arbre inaccessibles avant réparation.
# {biome} Nom ou identifiant du biome affiché.
# {biomes} Biomes dont les modifications ne s'appliquent qu'après un redémarrage du serveur.
# {block} Type ou description du bloc inspecté.
# {blockX} Coordonnée X du bloc ou de la destination de téléportation.
# {blockY} Coordonnée Y du bloc ou de la destination de téléportation.
@@ -55,6 +55,7 @@
# {befb} החלק המעוצב בתווית זמני המנוע שלפני הסוגריים המרובעים.
# {before} הערך לפני השינוי, או בלוקי העץ הבלתי נגישים לפני תיקון.
# {biome} שם הביומה או המזהה שלה.
# {biomes} ביומים שהשינויים בהם יחולו רק לאחר הפעלה מחדש של השרת.
# {block} סוג הבלוק הנבדק או תיאורו.
# {blockX} קואורדינטת X של הבלוק או יעד השיגור.
# {blockY} קואורדינטת Y של הבלוק או יעד השיגור.
@@ -50,6 +50,7 @@
# {befb} Parte formattata di un’etichetta dei tempi del motore prima della porzione tra parentesi quadre.
# {before} Valore prima della modifica o blocchi dell’albero irraggiungibili prima della riparazione.
# {biome} Nome o identificatore del bioma visualizzato.
# {biomes} Biomi le cui modifiche si applicano solo dopo un riavvio del server.
# {block} Tipo o descrizione del blocco esaminato.
# {blockX} Coordinata X del blocco o della destinazione del teletrasporto.
# {blockY} Coordinata Y del blocco o della destinazione del teletrasporto.
@@ -53,6 +53,7 @@
# {befb} エンジン処理時間ラベルの括弧部分より前にある書式付きテキスト。
# {before} 変更前の値、または修復前に接続されていなかった木のブロック数。
# {biome} 表示中のバイオームの名前または識別子。
# {biomes} サーバーの再起動後にのみ変更が反映されるバイオーム。
# {block} 調べているブロックの種類または説明。
# {blockX} ブロックまたはテレポート先の X 座標。
# {blockY} ブロックまたはテレポート先の Y 座標。
@@ -53,6 +53,7 @@
# {befb} 엔진 처리 시간 라벨에서 괄호 앞에 오는 서식 지정 텍스트.
# {before} 변경 전 값 또는 수리 전에 연결되지 않았던 나무 블록 수.
# {biome} 표시 중인 생물 군계의 이름 또는 식별자.
# {biomes} 서버를 재시작해야 변경 사항이 적용되는 생물 군계.
# {block} 조사 중인 블록의 종류 또는 설명.
# {blockX} 블록 또는 순간 이동 목적지의 X 좌표.
# {blockY} 블록 또는 순간 이동 목적지의 Y 좌표.
@@ -55,6 +55,7 @@
# {befb} Suformatuota variklio laiko žymos dalis prieš laužtinius skliaustus.
# {before} Reikšmė prieš pakeitimą arba nepasiekiami medžio blokai prieš taisymą.
# {biome} Rodomo biomo pavadinimas arba identifikatorius.
# {biomes} Biomai, kurių pakeitimai įsigalioja tik paleidus serverį iš naujo.
# {block} Tikrinamo bloko tipas arba aprašymas.
# {blockX} Bloko arba teleportacijos vietos X koordinatė.
# {blockY} Bloko arba teleportacijos vietos Y koordinatė.
@@ -50,6 +50,7 @@
# {befb} Opgemaakt deel van een motortijdmetingslabel vóór het gedeelte tussen vierkante haken.
# {before} Waarde vóór de wijziging, of onbereikbare boomblokken vóór reparatie.
# {biome} Naam of identificatie van het getoonde bioom.
# {biomes} Biomen waarvan de wijzigingen pas na een serverherstart gelden.
# {block} Type of beschrijving van het onderzochte blok.
# {blockX} X-coördinaat van het blok of de teleportbestemming.
# {blockY} Y-coördinaat van het blok of de teleportbestemming.
@@ -55,6 +55,7 @@
# {befb} Sformatowana część etykiety czasu silnika przed fragmentem w nawiasach kwadratowych.
# {before} Wartość przed zmianą albo niedostępne bloki drzewa przed naprawą.
# {biome} Nazwa lub identyfikator wyświetlanego biomu.
# {biomes} Biomy, których zmiany zaczną działać dopiero po restarcie serwera.
# {block} Typ lub opis sprawdzanego bloku.
# {blockX} Współrzędna X bloku lub celu teleportacji.
# {blockY} Współrzędna Y bloku lub celu teleportacji.
@@ -50,6 +50,7 @@
# {befb} Parte formatada de uma etiqueta de tempos do motor antes do trecho entre parênteses retos.
# {before} Valor anterior à alteração ou blocos de árvore inacessíveis antes da reparação.
# {biome} Nome ou identificador do bioma apresentado.
# {biomes} Biomas cujas alterações só se aplicam após reiniciar o servidor.
# {block} Tipo ou descrição do bloco inspecionado.
# {blockX} Coordenada X do bloco ou do destino de teletransporte.
# {blockY} Coordenada Y do bloco ou do destino de teletransporte.
@@ -55,6 +55,7 @@
# {befb} Оформленная часть метки времени движка перед фрагментом в квадратных скобках.
# {before} Значение до изменения либо недоступные блоки дерева до исправления.
# {biome} Имя или идентификатор отображаемого биома.
# {biomes} Биомы, изменения которых применяются только после перезапуска сервера.
# {block} Тип или описание проверяемого блока.
# {blockX} Координата X блока или точки телепортации.
# {blockY} Координата Y блока или точки телепортации.
@@ -55,6 +55,7 @@
# {befb} Motor zamanlama etiketinin köşeli parantezli bölümünden önceki biçimlendirilmiş kısmı.
# {before} Değişiklikten önceki değer veya onarım öncesi erişilemeyen ağaç blokları.
# {biome} Gösterilen biyomun adı veya kimliği.
# {biomes} Değişiklikleri yalnızca sunucu yeniden başlatıldıktan sonra geçerli olan biyomlar.
# {block} İncelenen bloğun türü veya açıklaması.
# {blockX} Bloğun veya ışınlanma hedefinin X koordinatı.
# {blockY} Bloğun veya ışınlanma hedefinin Y koordinatı.
@@ -53,6 +53,7 @@
# {befb} Phần văn bản đã định dạng trước đoạn trong ngoặc của nhãn thời gian xử lý.
# {before} Giá trị trước thay đổi hoặc số khối cây chưa nối được trước sửa chữa.
# {biome} Tên hoặc mã định danh quần xã đang hiển thị.
# {biomes} Các quần xã có thay đổi chỉ áp dụng sau khi khởi động lại máy chủ.
# {block} Loại hoặc mô tả khối đang kiểm tra.
# {blockX} Tọa độ X của khối hoặc điểm dịch chuyển.
# {blockY} Tọa độ Y của khối hoặc điểm dịch chuyển.
@@ -53,6 +53,7 @@
# {befb} 引擎耗时标签中括号部分之前的已格式化文本。
# {before} 更改前的值,或修复前无法连通的树木方块数。
# {biome} 正在显示的生物群系名称或标识符。
# {biomes} 其更改仅在服务器重启后生效的生物群系。
# {block} 正在检查的方块类型或描述。
# {blockX} 方块或传送目的地的 X 坐标。
# {blockY} 方块或传送目的地的 Y 坐标。
@@ -53,6 +53,7 @@
# {befb} 引擎耗時標籤中括號部分之前的已格式化文字。
# {before} 變更前的值,或修復前無法連通的樹木方塊數。
# {biome} 正在顯示的生態域名稱或識別碼。
# {biomes} 其變更僅在伺服器重新啟動後生效的生態域。
# {block} 正在檢查的方塊類型或描述。
# {blockX} 方塊或傳送目的地的 X 座標。
# {blockY} 方塊或傳送目的地的 Y 座標。
@@ -84,6 +84,16 @@ public class IrisSettingsDefaultsTest {
assertEquals(256, changed.getGenerator().getGenerationTransitionWidthBlocks());
}
@Test
public void studioValidatesAfterHotloadUnlessConfigured() {
assertFalse(new IrisSettings().getStudio().isValidateBeforeHotload());
assertFalse(new Gson().fromJson("{\"studio\":{}}", IrisSettings.class).getStudio().isValidateBeforeHotload());
IrisSettings changed = IrisSettings.parseHotloadSnapshot("{\"studio\":{\"validateBeforeHotload\":true}}");
assertTrue(changed.getStudio().isValidateBeforeHotload());
}
@Test
public void hotloadSnapshotIsValidatedBeforeReplacingLiveSettings() {
IrisSettings previous = IrisSettings.settings;
@@ -138,7 +138,7 @@ public class EngineHotloaderRecoveryTest {
try (MockedStatic<StudioGenerationUpdate> updates = mockStatic(StudioGenerationUpdate.class);
MockedStatic<IrisBoundarySignatureSampler> signatures = mockStatic(IrisBoundarySignatureSampler.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.class)) {
updates.when(() -> StudioGenerationUpdate.prepare(engine, history)).thenReturn(update);
updates.when(() -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.AFTER_ACTIVATION)).thenReturn(update);
configuration.when(IrisSettings::get).thenReturn(settings);
IllegalStateException thrown = assertThrows(IllegalStateException.class,
@@ -5,6 +5,7 @@ import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.world.history.GenerationActivation;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
import art.arcane.iris.world.history.IrisBoundarySignatureSampler;
@@ -66,7 +67,7 @@ public class EngineHotloaderRetirementTest {
}
});
planning.get(5L, TimeUnit.SECONDS);
return null;
return mock(GenerationActivation.class);
}).when(cutover).promotePending();
StudioGenerationUpdate update = mock(StudioGenerationUpdate.class);
IrisSettings settings = mock(IrisSettings.class, RETURNS_DEEP_STUBS);
@@ -76,7 +77,7 @@ public class EngineHotloaderRetirementTest {
MockedStatic<IrisStructureLocator> structures = mockStatic(IrisStructureLocator.class);
MockedStatic<StructureReachability> reachability = mockStatic(StructureReachability.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.class)) {
updates.when(() -> StudioGenerationUpdate.prepare(engine, history)).thenReturn(update);
updates.when(() -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.AFTER_ACTIVATION)).thenReturn(update);
configuration.when(IrisSettings::get).thenReturn(settings);
new EngineHotloader(engine).hotloadSilently();
@@ -4,6 +4,7 @@ import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryPaths;
import art.arcane.iris.world.history.GenerationPackFingerprint;
import art.arcane.iris.world.history.PackTreeState;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -15,6 +16,7 @@ import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
@@ -30,45 +32,80 @@ public final class StudioGenerationUpdateTest {
public final TemporaryFolder temporary = new TemporaryFolder();
@Test
public void unchangedSourceNeedsNoSnapshotOrManifestUpdate() throws Exception {
public void unchangedSourceNeedsNoManifestUpdateAndLeavesNoSnapshot() throws Exception {
Path source = temporary.newFolder("unchanged-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
assertUnchangedSourceStagesNothing(source, source);
}
@Test
public void unchangedAuthoringRootAliasNeedsNoManifestUpdate() throws Exception {
Path source = temporary.newFolder("unchanged-alias-target").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
Path alias = temporary.getRoot().toPath().resolve("unchanged-alias");
Files.createSymbolicLink(alias, source);
assertUnchangedSourceStagesNothing(alias, source);
assertThrows(IOException.class, () -> GenerationPackFingerprint.compute(alias, GenerationPackFingerprint.CURRENT_VERSION));
}
@Test
public void sourceMatchingTheActivatedRecordNeedsNoSnapshot() throws Exception {
Path source = temporary.newFolder("recorded-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(source);
when(history.activeEpoch()).thenReturn(active);
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn(fingerprint);
when(active.epochId()).thenReturn("a".repeat(64));
ActivatedStudioSource recorded = new ActivatedStudioSource("a".repeat(64), PackTreeState.capture(source));
assertNull(StudioGenerationUpdate.prepare(engine, history));
assertNull(StudioGenerationUpdate.prepare(engine, history, recorded, StudioPackValidation.BEFORE_ACTIVATION));
verify(history).activeEpoch();
verifyNoMoreInteractions(history);
}
@Test
public void unchangedAuthoringRootAliasNeedsNoSnapshot() throws Exception {
Path source = temporary.newFolder("unchanged-alias-target").toPath();
public void recordOfAnotherEpochIsIgnored() throws Exception {
Path source = temporary.newFolder("stale-record-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
Path alias = temporary.getRoot().toPath().resolve("unchanged-alias");
Files.createSymbolicLink(alias, source);
GenerationEpoch active = mock(GenerationEpoch.class);
when(active.epochId()).thenReturn("a".repeat(64));
ActivatedStudioSource stale = new ActivatedStudioSource("b".repeat(64), PackTreeState.capture(source));
assertTrue(stale.sourceStateOf(active).isEmpty());
}
private void assertUnchangedSourceStagesNothing(Path authoringRoot, Path source) throws Exception {
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
GenerationHistoryPaths paths = GenerationHistoryPaths.forDimension(temporary.newFolder().toPath());
Files.createDirectories(paths.generationRoot());
Files.writeString(paths.manifest(), "unchanged manifest");
IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(alias);
when(engine.getStudioGenerationSource()).thenReturn(authoringRoot);
when(history.activeEpoch()).thenReturn(active);
when(history.paths()).thenReturn(paths);
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn(fingerprint);
assertNull(StudioGenerationUpdate.prepare(engine, history));
assertNull(StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.BEFORE_ACTIVATION));
assertThrows(IOException.class, () -> GenerationPackFingerprint.compute(alias, GenerationPackFingerprint.CURRENT_VERSION));
assertEquals("unchanged manifest", Files.readString(paths.manifest()));
try (Stream<Path> entries = Files.list(paths.generationRoot())) {
assertEquals(1L, entries.count());
}
verify(history).activeEpoch();
verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history);
}
@@ -91,7 +128,7 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.BEFORE_ACTIVATION));
assertTrue(failure.getMessage(), failure.getMessage().contains(
"Studio pack update is invalid: Dimension 'test' declares no regions."));
@@ -101,6 +138,7 @@ public final class StudioGenerationUpdateTest {
}
verify(history, times(2)).activeEpoch();
verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history);
}
@@ -117,13 +155,36 @@ public final class StudioGenerationUpdateTest {
when(engine.getStudioGenerationSource()).thenReturn(alias);
GenerationHistory history = mock(GenerationHistory.class);
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.BEFORE_ACTIVATION));
assertTrue(failure.getMessage(), failure.getMessage().contains("rejected symbolic link"));
assertTrue(failure.getMessage(), failure.getMessage().contains("Pack contains a symbolic link"));
verifyNoInteractions(history);
}
}
@Test
public void validationAfterActivationDoesNotRejectAnInvalidPackInPrepare() throws Exception {
Path source = temporary.newFolder("unvalidated-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
GenerationHistoryPaths paths = GenerationHistoryPaths.forDimension(temporary.newFolder("unvalidated-world").toPath());
Files.createDirectories(paths.generationRoot());
IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(source);
when(history.activeEpoch()).thenReturn(active);
when(history.paths()).thenReturn(paths);
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64));
Throwable failure = assertThrows(Throwable.class, () -> StudioGenerationUpdate.prepare(
engine, history, null, StudioPackValidation.AFTER_ACTIVATION));
assertFalse(String.valueOf(failure.getMessage()),
String.valueOf(failure.getMessage()).contains("Studio pack update is invalid"));
}
@Test
public void invalidPackLeavesManifestUntouchedAndRemovesItsTemporarySnapshot() throws Exception {
Path source = temporary.newFolder("invalid-pack").toPath();
@@ -141,15 +202,16 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.BEFORE_ACTIVATION));
assertTrue(failure.getMessage().contains("Missing dimensions/ folder"));
assertTrue(failure.getMessage(), failure.getMessage().contains("Missing dimensions/ folder"));
assertEquals("unchanged manifest", Files.readString(paths.manifest()));
try (Stream<Path> entries = Files.list(paths.generationRoot())) {
assertEquals(1L, entries.count());
}
verify(history, times(2)).activeEpoch();
verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history);
}
@@ -174,7 +236,7 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null, StudioPackValidation.BEFORE_ACTIVATION));
assertTrue(failure.getMessage(), failure.getMessage().contains(
"Dimension 'test' structures[0].anchor must be omitted, null, or LEGACY for nativeStructures."));
@@ -184,6 +246,7 @@ public final class StudioGenerationUpdateTest {
}
verify(history, times(2)).activeEpoch();
verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history);
}
}
@@ -0,0 +1,71 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.pack.PackValidationResult;
import art.arcane.iris.pack.PackValidator;
import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.GenerationHistory;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class StudioPackAuditTest {
private static final String ACTIVE_EPOCH = "a".repeat(64);
private static final String SUPERSEDED_EPOCH = "b".repeat(64);
@Rule
public final TemporaryFolder temporary = new TemporaryFolder();
@Test
public void blockingErrorsOfTheActiveEpochAreReported() throws Exception {
List<String> reports = new ArrayList<>();
audit(ACTIVE_EPOCH, false, reports).report(invalidAnchorValidation());
assertEquals(1, reports.size());
assertTrue(reports.getFirst(), reports.getFirst().startsWith("Pack validation: "));
assertTrue(reports.getFirst(), reports.getFirst().contains(
"Dimension 'test' structures[0].anchor must be omitted, null, or LEGACY for nativeStructures."));
}
@Test
public void supersededEpochsAndClosedEnginesStayQuiet() throws Exception {
List<String> reports = new ArrayList<>();
PackValidationResult invalid = invalidAnchorValidation();
audit(SUPERSEDED_EPOCH, false, reports).report(invalid);
audit(ACTIVE_EPOCH, true, reports).report(invalid);
assertTrue(reports.isEmpty());
}
private StudioPackAudit audit(String epochId, boolean engineClosed, List<String> reports) {
IrisEngine engine = mock(IrisEngine.class);
when(engine.isClosed()).thenReturn(engineClosed);
when(engine.getPackSource()).thenReturn(temporary.getRoot().toPath().resolve("test-pack"));
GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class);
when(history.activeEpoch()).thenReturn(active);
when(active.epochId()).thenReturn(ACTIVE_EPOCH);
return new StudioPackAudit(engine, history, epochId, reports::add);
}
private PackValidationResult invalidAnchorValidation() throws Exception {
Path pack = temporary.newFolder().toPath();
Files.createDirectories(pack.resolve("dimensions"));
Files.writeString(pack.resolve("dimensions/test.json"), """
{"structures":[{"placementId":"village","anchor":"SURFACE",
"nativeStructures":[{"structure":"minecraft:village_plains"}]}]}
""");
return PackValidator.validate(pack.toFile());
}
}
@@ -0,0 +1,73 @@
package art.arcane.iris.pack;
import art.arcane.volmlib.util.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class PackValidationIoRunTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void secondValidationSeesFileEditedAfterFirst() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}");
write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}");
write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}");
assertTrue(PackValidator.validate(pack).isLoadable());
write(pack, "biomes/biome.json", "{\"name\":\"Biome\",\"fluidBodies\":{}}");
PackValidationResult edited = PackValidator.validate(pack);
assertFalse(edited.isLoadable());
assertTrue(edited.getBlockingErrors().toString().contains("Biome 'biome' declares removed field 'fluidBodies'"));
}
@Test
public void parsedJsonIsSharedOnlyWithinOneRun() throws Exception {
File pack = temporaryFolder.newFolder("shared");
File biome = write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}");
JSONObject[] withinRun = PackValidationIo.withinValidationRun(
() -> new JSONObject[]{PackValidationIo.readJson(biome), PackValidationIo.readJson(biome)});
assertSame(withinRun[0], withinRun[1]);
assertNotSame(PackValidationIo.readJson(biome), PackValidationIo.readJson(biome));
}
@Test
public void listingWithinRunIsACopyPerCaller() throws Exception {
File pack = temporaryFolder.newFolder("listing");
write(pack, "biomes/a.json", "{}");
write(pack, "biomes/b.json", "{}");
File biomes = new File(pack, "biomes");
int secondListingSize = PackValidationIo.withinValidationRun(() -> {
List<File> first = PackValidationIo.listJsonRecursive(biomes);
first.clear();
return PackValidationIo.listJsonRecursive(biomes).size();
});
assertEquals(2, secondListingSize);
}
private File write(File root, String relative, String content) throws Exception {
Path path = root.toPath().resolve(relative);
Files.createDirectories(path.getParent());
Files.writeString(path, content, StandardCharsets.UTF_8);
return path.toFile();
}
}
@@ -341,6 +341,7 @@ public class PackRuntimeStateGateTest {
holder("art.arcane.iris.world.history.NativeTerrainReceipt", "DEFLATERS", Kind.SCRATCH, "a reusable zlib deflater, no engine or pack reference"),
holder("art.arcane.iris.world.history.SavedBiomeStore", "DEFLATERS", Kind.SCRATCH, "a reusable zlib deflater, no engine or pack reference"),
holder("art.arcane.iris.world.storage.matter.IrisMatterContext", "DATA", Kind.SCRATCH, "a scoped pack data binding removed when the thread's outermost scope closes"),
holder("art.arcane.iris.pack.PackValidationIo", "ACTIVE_RUN", Kind.SCRATCH, "parsed pack files of one validation run, removed when the outermost run closes"),
holder("art.arcane.iris.world.tree.TreeSVC", "REENTRANT", Kind.SCRATCH, "a reentrancy flag, no engine or pack reference"),
holder("art.arcane.iris.structure.nativegen.NativeStructureOwnershipStore", "STATES", Kind.STATIC, "live-engine registry; a closed engine releases its store in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex", "INDEXES", Kind.STATIC, "live-engine registry; a closed engine uninstalls its index in the shutdown sequence (EngineShutdownDrainTest)"),
@@ -0,0 +1,44 @@
package art.arcane.iris.world.history;
import org.mockito.MockedStatic;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.mockito.Mockito.mockStatic;
/**
* Records directory channels opened on the calling thread, which is how directory fsyncs are issued.
*/
final class DirectorySyncCounter {
private DirectorySyncCounter() {
}
static List<Path> openedDirectories(IoAction action) throws Exception {
List<Path> opened = new CopyOnWriteArrayList<>();
try (MockedStatic<FileChannel> ignored = mockStatic(FileChannel.class, invocation -> {
if (invocation.getMethod().getName().equals("open")
&& invocation.getArgument(0) instanceof Path path
&& Files.isDirectory(path)) {
opened.add(path.toAbsolutePath().normalize());
}
return invocation.callRealMethod();
})) {
action.run();
}
return opened;
}
static long countUnder(Path root, List<Path> opened) {
Path normalizedRoot = root.toAbsolutePath().normalize();
return opened.stream().filter(path -> path.startsWith(normalizedRoot)).count();
}
@FunctionalInterface
interface IoAction {
void run() throws Exception;
}
}
@@ -1,6 +1,7 @@
package art.arcane.iris.world.history;
import art.arcane.iris.testsupport.DurabilityMode;
import art.arcane.iris.world.storage.Durability;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Assume;
@@ -43,6 +44,30 @@ public class GenerationHistoryStoreTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void onlySyncingPoliciesForceManifestAndEpochMetadata() throws Exception {
String previous = System.getProperty(Durability.MODE_PROPERTY);
System.clearProperty(Durability.MODE_PROPERTY);
try {
assertTrue(storeDirectorySyncs("durable-store", EpochPolicy.DURABLE) > 0);
assertEquals(0L, storeDirectorySyncs("studio-store", EpochPolicy.STUDIO));
} finally {
if (previous != null) {
System.setProperty(Durability.MODE_PROPERTY, previous);
}
}
}
private long storeDirectorySyncs(String name, EpochPolicy policy) throws Exception {
Path directory = temporaryFolder.getRoot().toPath().resolve(name).resolve("generation");
Files.createDirectories(directory.getParent());
List<Path> opened = DirectorySyncCounter.openedDirectories(() -> {
GenerationHistoryStore store = GenerationHistoryStore.initialize(directory, epoch(PACK_A), policy);
store.preparePendingActivation(epoch(PACK_B), 256);
});
return DirectorySyncCounter.countUnder(directory.getParent(), opened);
}
@Test
public void persistsActiveAndPendingHistoryAcrossReopen() throws Exception {
Path directory = temporaryFolder.getRoot().toPath().resolve("generation");
@@ -1,5 +1,7 @@
package art.arcane.iris.world.history;
import art.arcane.iris.world.storage.Durability;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -65,6 +67,70 @@ public class GenerationHistoryTest extends GenerationHistorySupport {
}
}
@Test
public void onlyDurableHistoriesSyncTheEpochTreeWhenStaging() throws Exception {
String previous = System.getProperty(Durability.MODE_PROPERTY);
System.clearProperty(Durability.MODE_PROPERTY);
try {
assertEquals(1, stagingEpochTreeSyncs("durable", EpochPolicy.DURABLE));
assertEquals(0, stagingEpochTreeSyncs("studio", EpochPolicy.STUDIO));
} finally {
if (previous != null) {
System.setProperty(Durability.MODE_PROPERTY, previous);
}
}
}
@Test
public void studioHistoryStagesAndPromotesAVerifiedTreeWithoutHashingItAgain() throws Exception {
Path world = temporaryFolder.newFolder("verified-stage-world").toPath();
Path packA = createPack("verified-stage-a", "alpha");
Path packB = createPack("verified-stage-b", "beta");
GenerationHistory history = GenerationHistory.create(world, packA, fingerprint(packA), 42L, contract(),
GenerationRegistryContract.empty(), EpochPolicy.STUDIO);
Path tree = history.paths().generationRoot().resolve(".studio-test");
GenerationPackRepository.snapshotPackTree(packB, tree, history.activePackLinkBasis().orElseThrow(), null);
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = mockStatic(GenerationPackFingerprint.class, invocation -> {
if (invocation.getMethod().getName().equals("compute")) {
hashes.incrementAndGet();
}
return invocation.callRealMethod();
})) {
GenerationActivation pending = history.stageVerifiedUpdate(
verified, contract(), GenerationRegistryContract.empty(), 0);
history.promotePending(List.of());
history.packRoot(pending.activationId());
assertEquals(0, hashes.get());
}
assertFalse(Files.exists(tree));
assertEquals(verified.fingerprint(), history.activeEpoch().packFingerprint());
assertEquals(verified.fingerprint(), fingerprint(history.activePackRoot()));
}
private int stagingEpochTreeSyncs(String name, EpochPolicy policy) throws Exception {
Path world = temporaryFolder.newFolder(name + "-staging-world").toPath();
Path packA = createPack(name + "-staging-a", "alpha");
Path packB = createPack(name + "-staging-b", "beta");
GenerationHistory history = GenerationHistory.create(world, packA, fingerprint(packA), 42L, contract(),
GenerationRegistryContract.empty(), policy);
AtomicInteger treeSyncs = new AtomicInteger();
try (MockedStatic<GenerationPackRepository> ignored = mockStatic(GenerationPackRepository.class, invocation -> {
if (invocation.getMethod().getName().equals("forceDirectoryTree") && invocation.getArguments().length == 2) {
treeSyncs.incrementAndGet();
}
return invocation.callRealMethod();
})) {
stage(history, packB);
}
Path stagedPack = history.packRoot(history.pendingActivation().orElseThrow().activationId());
assertEquals(fingerprint(packB), fingerprint(stagedPack));
return treeSyncs.get();
}
@Test
public void firstPackAccessRejectsTamperingAfterCreation() throws Exception {
Path world = temporaryFolder.newFolder("tampered-publication-world").toPath();
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.world.storage.Durability;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test;
@@ -9,11 +10,13 @@ import org.mockito.MockedStatic;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -49,6 +52,178 @@ public class GenerationPackRepositoryTest {
));
}
@Test
public void publishLinksUnchangedFilesFromTheBasisPackAndCopiesChangedOnes() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("basis-world").toPath();
Path first = createPack("basis-first", "{}");
Files.createDirectories(first.resolve("biomes"));
Files.writeString(first.resolve("biomes/plains.json"), "{\"name\":\"plains\"}");
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot);
Path basis = repository.publish(digest('1'), fingerprint(first), GenerationPackFingerprint.CURRENT_VERSION, first);
Path second = createPack("basis-second", "{\"changed\":true}");
Files.createDirectories(second.resolve("biomes"));
Files.writeString(second.resolve("biomes/plains.json"), "{\"name\":\"plains\"}");
Files.writeString(second.resolve("biomes/desert.json"), "{\"name\":\"desert\"}");
Path published = repository.publish(
digest('2'), fingerprint(second), GenerationPackFingerprint.CURRENT_VERSION, second, basis);
assertTrue(Files.isSameFile(basis.resolve("biomes/plains.json"), published.resolve("biomes/plains.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), published.resolve("dimensions/main.json")));
assertEquals("{\"changed\":true}", Files.readString(published.resolve("dimensions/main.json")));
assertEquals("{}", Files.readString(basis.resolve("dimensions/main.json")));
assertEquals("{\"name\":\"desert\"}", Files.readString(published.resolve("biomes/desert.json")));
assertEquals(fingerprint(second), fingerprint(published));
}
@Test
public void unsyncedRepositoryPublishesTheSamePackWithoutDirectorySyncs() throws Exception {
Path source = createPack("unsynced-source", "{}");
Path syncedWorld = temporaryFolder.newFolder("synced-world").toPath();
Path unsyncedWorld = temporaryFolder.newFolder("unsynced-world").toPath();
GenerationPackRepository synced = new GenerationPackRepository(syncedWorld, EpochPolicy.DURABLE);
GenerationPackRepository unsynced = new GenerationPackRepository(unsyncedWorld, EpochPolicy.STUDIO);
List<Path> syncedOpens = DirectorySyncCounter.openedDirectories(() -> synced.publish(
digest('a'), fingerprint(source), GenerationPackFingerprint.CURRENT_VERSION, source));
List<Path> unsyncedOpens = DirectorySyncCounter.openedDirectories(() -> unsynced.publish(
digest('a'), fingerprint(source), GenerationPackFingerprint.CURRENT_VERSION, source));
assertTrue(DirectorySyncCounter.countUnder(syncedWorld, syncedOpens) > 0);
assertEquals(0L, DirectorySyncCounter.countUnder(unsyncedWorld, unsyncedOpens));
assertEquals(fingerprint(source), fingerprint(unsynced.packRoot(digest('a'))));
}
@Test
public void defaultRepositoryFollowsTheGlobalDurabilityProperty() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("configured-world").toPath();
String previous = System.getProperty(Durability.MODE_PROPERTY);
try {
System.clearProperty(Durability.MODE_PROPERTY);
assertEquals(EpochPolicy.DURABLE, new GenerationPackRepository(dimensionRoot).policy());
System.setProperty(Durability.MODE_PROPERTY, "relaxed");
assertEquals(EpochPolicy.RELAXED, new GenerationPackRepository(dimensionRoot).policy());
} finally {
if (previous == null) {
System.clearProperty(Durability.MODE_PROPERTY);
} else {
System.setProperty(Durability.MODE_PROPERTY, previous);
}
}
}
@Test
public void scratchSnapshotCopiesThePackWithoutLinkingTheSource() throws Exception {
Path source = createPack("snapshot-source", "{}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, null, null);
assertEquals(fingerprint(source), fingerprint(snapshot));
assertFalse(Files.isSameFile(source.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
}
@Test
public void snapshotLinksUnchangedFilesToTheBasis() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("snapshot-basis-world").toPath();
Path first = createPack("snapshot-basis-first", "{}");
Files.writeString(first.resolve("biomes.json"), "{\"name\":\"plains\"}");
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot, EpochPolicy.STUDIO);
Path basis = repository.publish(digest('1'), fingerprint(first), GenerationPackFingerprint.CURRENT_VERSION, first);
Path source = createPack("snapshot-basis-source", "{\"changed\":true}");
Files.writeString(source.resolve("biomes.json"), "{\"name\":\"plains\"}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("basis-snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, basis, null);
assertTrue(Files.isSameFile(basis.resolve("biomes.json"), snapshot.resolve("biomes.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
assertEquals(fingerprint(source), fingerprint(snapshot));
}
@Test
public void recordedSourceStateLinksFilesByStampWithoutComparingContent() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("stamp-world").toPath();
Path source = createPack("stamp-source", "{}");
Files.writeString(source.resolve("biomes.json"), "{\"name\":\"plains\"}");
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot, EpochPolicy.STUDIO);
Path basis = repository.publish(digest('1'), fingerprint(source), GenerationPackFingerprint.CURRENT_VERSION, source);
PackTreeState recorded = PackTreeState.capture(source);
Files.writeString(basis.resolve("biomes.json"), "{\"name\":\"desert\"}");
Files.writeString(source.resolve("dimensions/main.json"), "{\"changed\":true}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("stamp-snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, basis, recorded);
assertTrue(Files.isSameFile(basis.resolve("biomes.json"), snapshot.resolve("biomes.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
assertEquals("{\"changed\":true}", Files.readString(snapshot.resolve("dimensions/main.json")));
}
@Test
public void packTreeStateNoticesRewrittenAddedAndIgnoredFiles() throws Exception {
Path source = createPack("state-source", "{}");
PackTreeState initial = PackTreeState.capture(source);
Files.createDirectories(source.resolve(".git"));
Files.writeString(source.resolve(".git/config"), "local");
Files.writeString(source.resolve("pack.code-workspace"), "{}");
assertEquals(initial, PackTreeState.capture(source));
Files.writeString(source.resolve("dimensions/main.json"), "{\"changed\":true}");
assertFalse(initial.equals(PackTreeState.capture(source)));
PackTreeState rewritten = PackTreeState.capture(source);
Files.writeString(source.resolve("dimensions/extra.json"), "{}");
assertFalse(rewritten.equals(PackTreeState.capture(source)));
}
@Test
public void studioRepositoryAdoptsAVerifiedTreeAndTrustsItsOwnVerification() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("adopt-world").toPath();
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot, EpochPolicy.STUDIO);
Path tree = Files.createDirectories(repository.generationRoot()).resolve("staged");
GenerationPackRepository.snapshotPackTree(createPack("adopt-source", "{}"), tree, null, null);
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = countingHashes(hashes)) {
Path published = repository.adopt(digest('a'), verified);
assertEquals(published, repository.requireExactPack(
digest('a'), verified.fingerprint(), verified.fingerprintVersion()));
assertEquals(0, hashes.get());
assertFalse(Files.exists(tree));
}
assertEquals(verified.fingerprint(), fingerprint(repository.packRoot(digest('a'))));
}
@Test
public void nonStudioRepositoriesStillHashOnEveryAccessAndRefuseAdoption() throws Exception {
Path source = createPack("rehash-source", "{}");
String expected = fingerprint(source);
GenerationPackRepository durable = new GenerationPackRepository(
temporaryFolder.newFolder("rehash-world").toPath(), EpochPolicy.DURABLE);
durable.publish(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION, source);
Path tree = Files.createDirectories(durable.generationRoot()).resolve("staged");
GenerationPackRepository.snapshotPackTree(source, tree, null, null);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = countingHashes(hashes)) {
durable.requireExactPack(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION);
durable.requireExactPack(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION);
}
assertEquals(2, hashes.get());
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
assertThrows(IllegalStateException.class, () -> durable.adopt(digest('b'), verified));
}
private static MockedStatic<GenerationPackFingerprint> countingHashes(AtomicInteger hashes) {
return mockStatic(GenerationPackFingerprint.class, invocation -> {
if (invocation.getMethod().getName().equals("compute")) {
hashes.incrementAndGet();
}
return invocation.callRealMethod();
});
}
@Test
public void rejectsMutationOfAnExistingEpoch() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath();