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 static class IrisSettingsStudio {
public boolean openVSCode = true; public boolean openVSCode = true;
public boolean blendChanges = true; public boolean blendChanges = true;
public boolean validateBeforeHotload = false;
public boolean disableTimeAndWeather = true; public boolean disableTimeAndWeather = true;
public boolean entitySpawning = true; public boolean entitySpawning = true;
public boolean autoStartDefaultStudio = false; 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.IrisStructureLocator;
import art.arcane.iris.structure.placement.StructureReachability; import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.generation.terrain.IrisDimension; 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.GenerationHistory;
import art.arcane.iris.world.history.IrisBoundarySignatureSampler; import art.arcane.iris.world.history.IrisBoundarySignatureSampler;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
@@ -50,6 +51,7 @@ import static art.arcane.iris.generation.runtime.EngineShutdownSequence.runClean
final class EngineHotloader { final class EngineHotloader {
private final IrisEngine engine; private final IrisEngine engine;
private final Object studioTransitionLock = new Object(); private final Object studioTransitionLock = new Object();
private ActivatedStudioSource activatedStudioSource;
EngineHotloader(IrisEngine engine) { EngineHotloader(IrisEngine engine) {
this.engine = engine; this.engine = engine;
@@ -235,7 +237,8 @@ final class EngineHotloader {
long startedAt = System.nanoTime(); long startedAt = System.nanoTime();
engine.requireRunning("hotload the Studio pack"); engine.requireRunning("hotload the Studio pack");
GenerationHistory history = router.history(); GenerationHistory history = router.history();
update = StudioGenerationUpdate.prepare(engine, history); StudioPackValidation validation = StudioPackValidation.configured();
update = StudioGenerationUpdate.prepare(engine, history, activatedStudioSource, validation);
if (update == null) { if (update == null) {
return; return;
} }
@@ -264,11 +267,11 @@ final class EngineHotloader {
IrisSettings settings = IrisSettings.get(); IrisSettings settings = IrisSettings.get();
int transitionWidth = settings.getStudio().isBlendChanges() int transitionWidth = settings.getStudio().isBlendChanges()
? settings.getGenerator().getGenerationTransitionWidthBlocks() : 0; ? settings.getGenerator().getGenerationTransitionWidthBlocks() : 0;
history.stageUpdate(update.source(), update.fingerprint(), update.dimensionContract(), history.stageVerifiedUpdate(update.pack(), update.dimensionContract(),
update.registryContract(), transitionWidth); update.registryContract(), transitionWidth);
} }
long stagedAt = System.nanoTime(); long stagedAt = System.nanoTime();
cutover.promotePending(); GenerationActivation activated = cutover.promotePending();
long promotedAt = System.nanoTime(); long promotedAt = System.nanoTime();
synchronized (engine.lifecycleLock) { synchronized (engine.lifecycleLock) {
if (engine.lifecycleState != LifecycleState.HOTLOADING) { if (engine.lifecycleState != LifecycleState.HOTLOADING) {
@@ -290,6 +293,10 @@ final class EngineHotloader {
StudioRestartRequirement requirement = StudioRestartRequirement.pending(update.pendingBiomes()); StudioRestartRequirement requirement = StudioRestartRequirement.pending(update.pendingBiomes());
publishRestartRequirement(requirement); publishRestartRequirement(requirement);
broadcastStudioHotload(false, restartNote(requirement)); broadcastStudioHotload(false, restartNote(requirement));
activatedStudioSource = update.activatedAs(activated.epochId());
if (validation == StudioPackValidation.AFTER_ACTIVATION) {
auditActivatedPack(history, activated);
}
} catch (Throwable failure) { } catch (Throwable failure) {
if (previous != null) { if (previous != null) {
synchronized (engine.lifecycleLock) { 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) { private void publishRestartRequirement(StudioRestartRequirement requirement) {
engine.studioRestartRequirement = requirement; engine.studioRestartRequirement = requirement;
if (requirement.isPending()) { 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.GenerationEpoch;
import art.arcane.iris.world.history.GenerationEpochContractFactory; import art.arcane.iris.world.history.GenerationEpochContractFactory;
import art.arcane.iris.world.history.GenerationHistory; 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.GenerationPackRepository;
import art.arcane.iris.world.history.GenerationRegistryContract; import art.arcane.iris.world.history.GenerationRegistryContract;
import art.arcane.iris.world.history.GenerationRegistryContractFactory; 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.StudioRegistryCapture;
import art.arcane.iris.world.history.VerifiedPackTree;
import art.arcane.iris.generation.terrain.IrisDimension; import art.arcane.iris.generation.terrain.IrisDimension;
import java.io.IOException; import java.io.IOException;
@@ -19,31 +20,44 @@ import java.nio.file.Path;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.List; 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( record StudioGenerationUpdate(
Path stagingRoot, Path stagingRoot,
Path source, VerifiedPackTree pack,
String fingerprint, PackTreeState sourceState,
GenerationEpoch.DimensionContract dimensionContract, GenerationEpoch.DimensionContract dimensionContract,
GenerationRegistryContract registryContract, GenerationRegistryContract registryContract,
List<String> pendingBiomes List<String> pendingBiomes
) implements AutoCloseable { ) 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(); Path source = engine.getStudioGenerationSource().toRealPath();
IrisData.invalidateLoadedAuthoringResources(source.toFile()); IrisData.invalidateLoadedAuthoringResources(source.toFile());
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION); PackTreeState sourceState = PackTreeState.capture(source);
GenerationEpoch active = history.activeEpoch(); PackTreeState activeSourceState = previous == null ? null
if (active.packFingerprintVersion() == GenerationPackFingerprint.CURRENT_VERSION : previous.sourceStateOf(history.activeEpoch()).orElse(null);
&& fingerprint.equals(active.packFingerprint())) { if (sourceState.equals(activeSourceState)) {
return null; return null;
} }
Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-"); Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-");
Path snapshot = stagingRoot.resolve(source.getFileName());
try { try {
GenerationPackRepository.copyPackTree(source, snapshot); StudioGenerationUpdate update = prepareStaged(
if (!fingerprint.equals(GenerationPackFingerprint.compute(snapshot, GenerationPackFingerprint.CURRENT_VERSION))) { engine, history, source, sourceState, activeSourceState, stagingRoot, validation);
throw new IOException("Studio pack changed while its update snapshot was being captured."); if (update == null) {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
} }
return prepareSnapshot(engine, history, stagingRoot, snapshot, fingerprint); return update;
} catch (Throwable failure) { } catch (Throwable failure) {
try { try {
AtomicDirectoryPublisher.deleteTree(stagingRoot); AtomicDirectoryPublisher.deleteTree(stagingRoot);
@@ -54,16 +68,39 @@ record StudioGenerationUpdate(
} }
} }
private static StudioGenerationUpdate prepareSnapshot(IrisEngine engine, GenerationHistory history, private static StudioGenerationUpdate prepareStaged(IrisEngine engine, GenerationHistory history, Path source,
Path stagingRoot, Path source, String fingerprint) PackTreeState sourceState, PackTreeState activeSourceState,
Path stagingRoot, StudioPackValidation validation)
throws IOException { throws IOException {
GenerationEpoch active = history.activeEpoch(); Path snapshot = stagingRoot.resolve(source.getFileName());
PackValidationResult validation = PackValidator.validate(source.toFile()); GenerationPackRepository.snapshotPackTree(
if (!validation.isLoadable()) { source, snapshot, history.activePackLinkBasis().orElse(null), activeSourceState);
throw new IOException("Studio pack update is invalid: " + String.join("; ", validation.getBlockingErrors())); 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 { try {
data.useVerifiedGenerationPackFingerprint(pack.fingerprint());
if (validation == StudioPackValidation.BEFORE_ACTIVATION) {
requireLoadable(pack, data);
}
IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey()); IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey());
if (replacement == null) { if (replacement == null) {
throw new IOException("Studio pack update is missing dimension '" 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."); throw new IOException("Studio pack update changes the world's immutable dimension layout.");
} }
StudioRegistryCapture registry = GenerationRegistryContractFactory.createRetainingLoadedBiomes( StudioRegistryCapture registry = GenerationRegistryContractFactory.createRetainingLoadedBiomes(
data, replacement, fingerprint, active.registryContract()); data, replacement, pack.fingerprint(), active.registryContract());
GenerationRegistryContract registryContract = registry.contract(); GenerationRegistryContract registryContract = registry.contract();
registryContract.requireDefinitionsAvailableIn( registryContract.requireDefinitionsAvailableIn(
GenerationRegistryContractFactory.captureRequiredDefinitions(List.of(registryContract))); 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()); registry.pendingBiomes());
} finally { } 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 @Override
public void close() throws IOException { public void close() throws IOException {
AtomicDirectoryPublisher.deleteTree(stagingRoot); 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("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("before", "Value before the change, or unreachable tree blocks before repair."),
Map.entry("biome", "Name or identifier of the biome being shown."), 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("block", "Block type or block description being inspected."),
Map.entry("blockX", "X coordinate of the block or teleport destination."), Map.entry("blockX", "X coordinate of the block or teleport destination."),
Map.entry("blockY", "Y 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.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@@ -540,7 +539,7 @@ public final class ContentKeyValidator {
boolean inEntities = relative.startsWith("entities/"); boolean inEntities = relative.startsWith("entities/");
JSONObject json; JSONObject json;
try { try {
json = new JSONObject(Files.readString(path, StandardCharsets.UTF_8)); json = PackValidationIo.parseJson(path.toFile());
} catch (Throwable ignored) { } catch (Throwable ignored) {
continue; continue;
} }
@@ -27,8 +27,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -58,7 +56,7 @@ final class PackDimensionValidator {
String dimensionKey = PackValidationIo.deriveKey(dimensionsFolder, dimFile); String dimensionKey = PackValidationIo.deriveKey(dimensionsFolder, dimFile);
JSONObject dimJson; JSONObject dimJson;
try { try {
dimJson = new JSONObject(Files.readString(dimFile.toPath(), StandardCharsets.UTF_8)); dimJson = PackValidationIo.parseJson(dimFile);
} catch (Throwable e) { } catch (Throwable e) {
blockingErrors.add("Dimension '" + dimensionKey + "' has invalid JSON: " + e.getMessage()); blockingErrors.add("Dimension '" + dimensionKey + "' has invalid JSON: " + e.getMessage());
continue; continue;
@@ -98,7 +96,7 @@ final class PackDimensionValidator {
JSONObject regionJson; JSONObject regionJson;
try { try {
regionJson = new JSONObject(Files.readString(regionFile.toPath(), StandardCharsets.UTF_8)); regionJson = PackValidationIo.parseJson(regionFile);
} catch (Throwable e) { } catch (Throwable e) {
blockingErrors.add("Region '" + regionKey + "' has invalid JSON: " + e.getMessage()); blockingErrors.add("Region '" + regionKey + "' has invalid JSON: " + e.getMessage());
continue; continue;
@@ -275,7 +273,7 @@ final class PackDimensionValidator {
blockingErrors.add(context + " references missing style snippet '" + reference + "'."); blockingErrors.add(context + " references missing style snippet '" + reference + "'.");
return; return;
} }
new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); PackValidationIo.parseJson(snippet.file());
} catch (Throwable error) { } catch (Throwable error) {
blockingErrors.add(context + " references invalid style snippet '" + reference + "': " blockingErrors.add(context + " references invalid style snippet '" + reference + "': "
+ error.getMessage()); + error.getMessage());
@@ -638,7 +636,7 @@ final class PackDimensionValidator {
return null; return null;
} }
try { try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); return PackValidationIo.parseJson(snippet.file());
} catch (Throwable e) { } catch (Throwable e) {
return null; return null;
} }
@@ -23,8 +23,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
@@ -69,7 +67,7 @@ final class PackGeneratorDuplicateValidator {
String key = PackValidationIo.deriveKey(generatorsFolder, generatorFile); String key = PackValidationIo.deriveKey(generatorsFolder, generatorFile);
String fingerprint; String fingerprint;
try { try {
fingerprint = fingerprint(new JSONObject(Files.readString(generatorFile.toPath(), StandardCharsets.UTF_8))); fingerprint = fingerprint(PackValidationIo.parseJson(generatorFile));
} catch (Throwable e) { } catch (Throwable e) {
continue; continue;
} }
@@ -99,7 +97,7 @@ final class PackGeneratorDuplicateValidator {
for (File biomeFile : PackValidationIo.listJsonRecursive(biomesFolder)) { for (File biomeFile : PackValidationIo.listJsonRecursive(biomesFolder)) {
JSONObject biome; JSONObject biome;
try { try {
biome = new JSONObject(Files.readString(biomeFile.toPath(), StandardCharsets.UTF_8)); biome = PackValidationIo.parseJson(biomeFile);
} catch (Throwable e) { } catch (Throwable e) {
continue; continue;
} }
@@ -131,7 +129,7 @@ final class PackGeneratorDuplicateValidator {
return null; return null;
} }
try { try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); return PackValidationIo.parseJson(snippet.file());
} catch (Throwable e) { } catch (Throwable e) {
return null; return null;
} }
@@ -27,7 +27,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@@ -59,7 +58,7 @@ final class PackSpawnValidator {
String spawnerKey = PackValidationIo.deriveKey(spawnersFolder, spawnerFile); String spawnerKey = PackValidationIo.deriveKey(spawnersFolder, spawnerFile);
JSONObject spawner; JSONObject spawner;
try { try {
spawner = new JSONObject(Files.readString(spawnerFile.toPath(), StandardCharsets.UTF_8)); spawner = PackValidationIo.parseJson(spawnerFile);
} catch (Throwable e) { } catch (Throwable e) {
blockingErrors.add("Spawner '" + spawnerKey + "' has invalid JSON: " + e.getMessage()); blockingErrors.add("Spawner '" + spawnerKey + "' has invalid JSON: " + e.getMessage());
continue; continue;
@@ -147,7 +146,7 @@ final class PackSpawnValidator {
} }
try { try {
new JSONObject(Files.readString(entityFile, StandardCharsets.UTF_8)); PackValidationIo.parseJson(entityFile.toFile());
validEntityFiles.add(entityFile); validEntityFiles.add(entityFile);
} catch (Throwable e) { } catch (Throwable e) {
String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
@@ -170,7 +169,7 @@ final class PackSpawnValidator {
String biomeKey = PackValidationIo.deriveKey(biomesFolder, biomeFile); String biomeKey = PackValidationIo.deriveKey(biomesFolder, biomeFile);
JSONObject biome; JSONObject biome;
try { try {
biome = new JSONObject(Files.readString(biomeFile.toPath(), StandardCharsets.UTF_8)); biome = PackValidationIo.parseJson(biomeFile);
} catch (Throwable e) { } catch (Throwable e) {
blockingErrors.add("Biome '" + biomeKey + "' has invalid JSON: " + e.getMessage()); blockingErrors.add("Biome '" + biomeKey + "' has invalid JSON: " + e.getMessage());
continue; continue;
@@ -9,7 +9,6 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.InvalidPathException; import java.nio.file.InvalidPathException;
import java.nio.file.Path; import java.nio.file.Path;
@@ -172,7 +171,7 @@ final class PackStaticObjectValidator {
return null; return null;
} }
try { try {
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); return PackValidationIo.parseJson(snippet.file());
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage()); errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage());
return null; return null;
@@ -27,8 +27,6 @@ import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
@@ -782,7 +780,7 @@ final class PackStructurePlacementValidator {
String resourceKey, String resourceKey,
List<String> blockingErrors) { List<String> blockingErrors) {
try { try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); return PackValidationIo.parseJson(file);
} catch (IOException | RuntimeException e) { } catch (IOException | RuntimeException e) {
String reason = e.getMessage(); String reason = e.getMessage();
if (reason == null || reason.isBlank()) { if (reason == null || reason.isBlank()) {
@@ -23,8 +23,6 @@ import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@@ -68,7 +66,7 @@ final class PackStyledRangeDefaultValidator {
String key = PackValidationIo.deriveKey(resourceFolder, resourceFile); String key = PackValidationIo.deriveKey(resourceFolder, resourceFile);
JSONObject json; JSONObject json;
try { try {
json = new JSONObject(Files.readString(resourceFile.toPath(), StandardCharsets.UTF_8)); json = PackValidationIo.parseJson(resourceFile);
} catch (Throwable e) { } catch (Throwable e) {
continue; continue;
} }
@@ -122,7 +120,7 @@ final class PackStyledRangeDefaultValidator {
return; // Missing snippets are reported by the content-key machinery. return; // Missing snippets are reported by the content-key machinery.
} }
try { try {
range = new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8)); range = PackValidationIo.parseJson(snippet.file());
via = " (via snippet '" + snippet.key() + "')"; via = " (via snippet '" + snippet.key() + "')";
} catch (Throwable e) { } catch (Throwable e) {
return; return;
@@ -26,18 +26,51 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Stream; import java.util.stream.Stream;
public final class PackValidationIo { public final class PackValidationIo {
private static final ThreadLocal<ValidationRunReads> ACTIVE_RUN = new ThreadLocal<>();
private PackValidationIo() { 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) { static JSONObject readJson(File file) {
try { try {
return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); return parseJson(file);
} catch (IOException | RuntimeException parseFailure) { } catch (IOException | RuntimeException parseFailure) {
// Every folder scanned through readJson is also scanned by a readGraphJson pass // Every folder scanned through readJson is also scanned by a readGraphJson pass
// (validateUnsupportedStructureTransforms / validateStructureStartPools), which records the // (validateUnsupportedStructureTransforms / validateStructureStartPools), which records the
@@ -80,6 +113,14 @@ public final class PackValidationIo {
} }
static List<File> listJsonRecursive(File root) { 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<>(); List<File> out = new ArrayList<>();
try (Stream<Path> stream = Files.walk(root.toPath())) { try (Stream<Path> stream = Files.walk(root.toPath())) {
stream.filter(Files::isRegularFile) stream.filter(Files::isRegularFile)
@@ -124,4 +165,38 @@ public final class PackValidationIo {
} }
return keys; 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) { 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) { public static PackValidationResult validateForDatapackBootstrap(File packFolder) {
return validate(packFolder, false); return validate(packFolder, false, null);
} }
public static PackValidationResult validateForPackaging(File packFolder) { 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) { 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(); String packName = packFolder == null ? "<unknown>" : packFolder.getName();
List<String> blockingErrors = new ArrayList<>(); List<String> blockingErrors = new ArrayList<>();
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
@@ -176,7 +190,7 @@ public final class PackValidator {
? IrisPlatforms.get().minecraftVersion() ? IrisPlatforms.get().minecraftVersion()
: null; : null;
List<CompatFinding> compatFindings = validateLiveRegistries List<CompatFinding> compatFindings = validateLiveRegistries
? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings) ? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings, loadedPack)
: List.of(); : List.of();
// Keys the version gate already names in its own line are not repeated as unknown-key findings. // 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, File[] dimensionFiles,
String minecraftVersion, String minecraftVersion,
List<String> blockingErrors, List<String> blockingErrors,
List<String> warnings List<String> warnings,
IrisData loadedPack
) { ) {
if (!IrisPlatforms.isBound()) { if (!IrisPlatforms.isBound()) {
return List.of(); return List.of();
} }
IrisData data = null; IrisData data = null;
try { try {
data = IrisData.openRuntime(packFolder); data = loadedPack == null ? IrisData.openRuntime(packFolder) : loadedPack;
if (!data.getContentGate().ready()) { if (!data.getContentGate().ready()) {
return List.of(); return List.of();
} }
@@ -223,7 +238,7 @@ public final class PackValidator {
+ ": " + Objects.requireNonNullElse(e.getMessage(), "No failure detail.")); + ": " + Objects.requireNonNullElse(e.getMessage(), "No failure detail."));
return List.of(); return List.of();
} finally { } finally {
if (data != null) { if (data != null && data != loadedPack) {
try { try {
data.close(); data.close();
} catch (Throwable closeFailure) { } catch (Throwable closeFailure) {
@@ -168,6 +168,10 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE) @Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
private transient volatile boolean generationPackFingerprintVerifiedByCaller;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
private transient volatile GenerationRegistryContract generationRegistryContract; private transient volatile GenerationRegistryContract generationRegistryContract;
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE) @Setter(AccessLevel.NONE)
@@ -265,6 +269,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
dump(); dump();
clearLists(); clearLists();
generationPackFingerprint = null; generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
contentGate = null; contentGate = null;
dimensionCustomBiomeResourceKeys.clear(); 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() { public boolean hasGenerationRegistryContract() {
return generationRegistryContract != null; return generationRegistryContract != null;
} }
@@ -750,6 +772,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
IrisObjectScale.invalidate(this); IrisObjectScale.invalidate(this);
contentGate = null; contentGate = null;
generationPackFingerprint = null; generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
synchronized (dimensionCustomBiomeResourceKeys) { synchronized (dimensionCustomBiomeResourceKeys) {
dimensionCustomBiomeResourceKeys.clear(); 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.ChunkContext;
import art.arcane.iris.generation.context.IrisContext; import art.arcane.iris.generation.context.IrisContext;
import art.arcane.volmlib.util.io.ReactiveFolder; 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.task.J;
import art.arcane.iris.world.runtime.WorldRuntimeControlService; import art.arcane.iris.world.runtime.WorldRuntimeControlService;
import art.arcane.volmlib.util.scheduling.Looper; import art.arcane.volmlib.util.scheduling.Looper;
@@ -132,7 +131,7 @@ import java.util.function.BooleanSupplier;
@Data @Data
public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChunkGenerator, Listener { public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChunkGenerator, Listener {
private static final int LOAD_LOCKS = Runtime.getRuntime().availableProcessors() * 4; 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 long HOTLOAD_MAINTENANCE_DELAY_MS = 4000L;
private static final int PLAYER_ENTRY_MOVE_PADDING = 3; private static final int PLAYER_ENTRY_MOVE_PADDING = 3;
private static final int SPAWN_HYDROLOGY_REACH = 256; 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 ReactiveFolder folder;
private final ReentrantLock lock = new ReentrantLock(); private final ReentrantLock lock = new ReentrantLock();
private final KList<BlockPopulator> populators; private final KList<BlockPopulator> populators;
private final ChronoLatch hotloadChecker;
private final AtomicBoolean setup; private final AtomicBoolean setup;
private final boolean studio; private final boolean studio;
private final AtomicBoolean studioEntryBootstrapActive; private final AtomicBoolean studioEntryBootstrapActive;
@@ -187,7 +185,6 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
populators = new KList<>(); populators = new KList<>();
loadLock = new GenerationStageGate(LOAD_LOCKS, () -> closing); loadLock = new GenerationStageGate(LOAD_LOCKS, () -> closing);
this.world = world; this.world = world;
this.hotloadChecker = new ChronoLatch(1000, false);
this.studio = studio; this.studio = studio;
this.studioEntryBootstrapActive = new AtomicBoolean(studio); this.studioEntryBootstrapActive = new AtomicBoolean(studio);
this.dataLocation = dataLocation; this.dataLocation = dataLocation;
@@ -849,10 +846,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun
return HOTLOAD_MAINTENANCE_DELAY_MS; return HOTLOAD_MAINTENANCE_DELAY_MS;
} }
if (hotloadChecker.flip()) { folder.check();
folder.check();
}
return HOTLOAD_LOOP_DELAY_MS; 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.studio.jigsaw.JigsawStudioActivation;
import art.arcane.iris.world.IrisToolbelt; import art.arcane.iris.world.IrisToolbelt;
import art.arcane.volmlib.util.cache.AtomicCache; 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.GenerationActivation;
import art.arcane.iris.world.history.GenerationEpoch; import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.GenerationEpochContractFactory; import art.arcane.iris.world.history.GenerationEpochContractFactory;
@@ -218,7 +219,17 @@ public class StudioSVC implements IrisService {
File dimensionRoot, File dimensionRoot,
long worldSeed 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( public IrisDimension replaceIntoWorld(
@@ -227,7 +238,8 @@ public class StudioSVC implements IrisService {
File dimensionRoot, File dimensionRoot,
long worldSeed 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(); return publication == null ? null : publication.dimension();
} }
@@ -248,7 +260,8 @@ public class StudioSVC implements IrisService {
IrisDimension dimension, IrisDimension dimension,
File dimensionRoot, File dimensionRoot,
long worldSeed, long worldSeed,
boolean stageUpdate boolean stageUpdate,
EpochPolicy epochPolicy
) { ) {
if (J.isPrimaryThread()) { if (J.isPrimaryThread()) {
sender.sendMessage(IrisLanguage.text( sender.sendMessage(IrisLanguage.text(
@@ -290,7 +303,8 @@ public class StudioSVC implements IrisService {
candidate.packFingerprint(), candidate.packFingerprint(),
worldSeed, worldSeed,
candidate.dimensionContract(), candidate.dimensionContract(),
candidate.registryContract() candidate.registryContract(),
epochPolicy
); );
} }
Path installedPack = stageUpdate && history.pendingActivation().isPresent() 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.volmlib.nativelib.server.NativeServerDiagnostics;
import art.arcane.iris.world.runtime.TransientWorldCleanupSupport; import art.arcane.iris.world.runtime.TransientWorldCleanupSupport;
import art.arcane.iris.world.runtime.WorldRuntimeControlService; import art.arcane.iris.world.runtime.WorldRuntimeControlService;
import art.arcane.iris.world.history.EpochPolicy;
import art.arcane.iris.world.history.GenerationHistory; import art.arcane.iris.world.history.GenerationHistory;
import com.google.common.util.concurrent.AtomicDouble; import com.google.common.util.concurrent.AtomicDouble;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
@@ -273,8 +274,9 @@ public class IrisCreator {
if (benchmark && !studio) { if (benchmark && !studio) {
installedDimension = studioService.installIntoTransientWorld(sender, resolvedDimension, dimensionRoot); installedDimension = studioService.installIntoTransientWorld(sender, resolvedDimension, dimensionRoot);
} else { } else {
EpochPolicy epochPolicy = studio ? EpochPolicy.STUDIO : EpochPolicy.configured();
StudioSVC.GenerationPublication publication = studioService.installIntoWorld( StudioSVC.GenerationPublication publication = studioService.installIntoWorld(
sender, resolvedDimension, dimensionRoot, seed); sender, resolvedDimension, dimensionRoot, seed, epochPolicy);
installedDimension = publication == null ? null : publication.dimension(); installedDimension = publication == null ? null : publication.dimension();
if (publication != null) { if (publication != null) {
publishedHistory = publication.history(); 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 dimensionRoot;
private final Path directory; private final Path directory;
private final EpochPolicy policy;
public GenerationBoundaryStore(Path dimensionRoot) { 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(); Path root = Objects.requireNonNull(dimensionRoot, "Dimension root").toAbsolutePath().normalize();
this.dimensionRoot = root; this.dimensionRoot = root;
this.directory = root.resolve("iris").resolve("generation").resolve("boundaries").normalize(); this.directory = root.resolve("iris").resolve("generation").resolve("boundaries").normalize();
@@ -224,7 +230,7 @@ public final class GenerationBoundaryStore {
".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock" ".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock"
)) { )) {
ensureDirectory(); ensureDirectory();
PublishedCatalog catalog = builder.publish(directory, activationId); PublishedCatalog catalog = builder.publish(directory, activationId, policy);
Path target = snapshotPath(activationId); Path target = snapshotPath(activationId);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
GenerationBoundary existing = load(activationId); GenerationBoundary existing = load(activationId);
@@ -236,7 +242,7 @@ public final class GenerationBoundaryStore {
} }
return existing; return existing;
} }
publishAtomic(target, catalog.encoded(), "generation boundary catalog"); publishAtomic(target, catalog.encoded(), "generation boundary catalog", policy);
return load(activationId); return load(activationId);
} }
} }
@@ -264,7 +270,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(directory); 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); Path child = parent.resolve(name);
if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) {
requireSafeDirectory(child); requireSafeDirectory(child);
@@ -276,7 +282,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(child); requireSafeDirectory(child);
return child; return child;
} }
forceDirectory(parent); forceDirectory(parent, policy);
return child; return child;
} }
@@ -357,7 +363,8 @@ public final class GenerationBoundaryStore {
return withChecksum(bodyBytes.toByteArray()); 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 directory = target.getParent();
Path temporary = Files.createTempFile(directory, ".boundary-", ".tmp"); Path temporary = Files.createTempFile(directory, ".boundary-", ".tmp");
try { try {
@@ -367,14 +374,16 @@ public final class GenerationBoundaryStore {
StandardOpenOption.TRUNCATE_EXISTING StandardOpenOption.TRUNCATE_EXISTING
)) { )) {
writeFully(channel, ByteBuffer.wrap(encoded)); writeFully(channel, ByteBuffer.wrap(encoded));
channel.force(true); if (policy.syncs()) {
channel.force(true);
}
} }
try { try {
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException error) { } catch (AtomicMoveNotSupportedException error) {
throw new IOException("Generation boundary " + kind + " publication requires an atomic move", error); throw new IOException("Generation boundary " + kind + " publication requires an atomic move", error);
} }
forceDirectory(directory); forceDirectory(directory, policy);
} finally { } finally {
Files.deleteIfExists(temporary); Files.deleteIfExists(temporary);
} }
@@ -483,8 +492,8 @@ public final class GenerationBoundaryStore {
} }
} }
private static void forceDirectory(Path path) throws IOException { private static void forceDirectory(Path path, EpochPolicy policy) throws IOException {
if (File.separatorChar == '\\') { if (!policy.syncs() || File.separatorChar == '\\') {
return; return;
} }
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) { 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) { if (masks.size() > MAX_REGION_COUNT) {
throw new IOException("Generation boundary exceeds the maximum region count"); throw new IOException("Generation boundary exceeds the maximum region count");
} }
@@ -529,7 +538,7 @@ public final class GenerationBoundaryStore {
sortRegionKeys(regionKeys); sortRegionKeys(regionKeys);
Long2ObjectOpenHashMap<String> shardHashes = new Long2ObjectOpenHashMap<>(regionKeys.length); Long2ObjectOpenHashMap<String> shardHashes = new Long2ObjectOpenHashMap<>(regionKeys.length);
for (long regionKey : regionKeys) { 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); shardHashes.put(regionKey, hash);
} }
byte[] identity = computeIdentity(activationId, chunkCount, regionKeys, shardHashes); byte[] identity = computeIdentity(activationId, chunkCount, regionKeys, shardHashes);
@@ -546,7 +555,7 @@ public final class GenerationBoundaryStore {
} }
private static final class MaskShard { 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); byte[] encoded = encode(mask);
String hash = sha256(encoded); String hash = sha256(encoded);
Path target = directory.resolve(maskFileName(hash)); Path target = directory.resolve(maskFileName(hash));
@@ -556,7 +565,7 @@ public final class GenerationBoundaryStore {
return hash; return hash;
} }
try { try {
publishAtomic(target, encoded, "mask shard"); publishAtomic(target, encoded, "mask shard", policy);
} catch (FileAlreadyExistsException race) { } catch (FileAlreadyExistsException race) {
requireRegularFile(target, "Generation boundary mask"); requireRegularFile(target, "Generation boundary mask");
read(target, hash); read(target, hash);
@@ -69,7 +69,7 @@ public final class GenerationHistory {
this.store = Objects.requireNonNull(store, "store"); this.store = Objects.requireNonNull(store, "store");
this.ownership = Objects.requireNonNull(ownership, "ownership"); this.ownership = Objects.requireNonNull(ownership, "ownership");
this.kernels = Objects.requireNonNull(kernels, "kernels"); 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.terrainSignatures = new TerrainBoundarySignatureStore(paths.dimensionRoot());
this.semantics = GenerationSemanticIndex.loadRequired(paths.dimensionRoot(), unpublished); this.semantics = GenerationSemanticIndex.loadRequired(paths.dimensionRoot(), unpublished);
this.savedBiomes = SavedBiomeStore.open(paths.dimensionRoot(), unpublished); this.savedBiomes = SavedBiomeStore.open(paths.dimensionRoot(), unpublished);
@@ -140,18 +140,33 @@ public final class GenerationHistory {
GenerationKernelRegistry kernels GenerationKernelRegistry kernels
) throws IOException { ) throws IOException {
return create(new FreshCreation(dimensionRoot, packSource, packFingerprint, worldSeed, dimensionContract, registryContract), 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 { public static GenerationHistory createUnpublished(FreshCreation creation) throws IOException {
Objects.requireNonNull(creation, "creation"); Objects.requireNonNull(creation, "creation");
Files.createDirectory(creation.dimensionRoot()); Files.createDirectory(creation.dimensionRoot());
GenerationKernelRegistry kernels = GenerationKernelRegistry.standard(); 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, 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 dimensionRoot = creation.dimensionRoot();
Path packSource = creation.packSource(); Path packSource = creation.packSource();
String packFingerprint = creation.packFingerprint(); String packFingerprint = creation.packFingerprint();
@@ -180,16 +195,16 @@ public final class GenerationHistory {
kernels kernels
); );
requireSourceFingerprint(packSource, epoch.packFingerprint(), epoch.packFingerprintVersion()); requireSourceFingerprint(packSource, epoch.packFingerprint(), epoch.packFingerprintVersion());
GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot()); GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot(), epochPolicy);
Path publishedPack = packs.publish( Path publishedPack = packs.publish(
epoch.epochId(), epoch.epochId(),
epoch.packFingerprint(), epoch.packFingerprint(),
epoch.packFingerprintVersion(), epoch.packFingerprintVersion(),
packSource packSource
); );
forceEpochPublication(paths, epoch.epochId()); forceEpochPublication(paths, epoch.epochId(), epochPolicy);
GenerationSemanticIndex.initialize(paths.dimensionRoot()); 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, return new GenerationHistory(paths, packs, store, ownership, kernels,
Optional.of(new FreshPublication(publishedPack, epoch)), unpublished); Optional.of(new FreshPublication(publishedPack, epoch)), unpublished);
} }
@@ -315,7 +330,7 @@ public final class GenerationHistory {
expectedEpoch.packFingerprint(), expectedEpoch.packFingerprint(),
expectedEpoch.packFingerprintVersion() expectedEpoch.packFingerprintVersion()
); );
forceEpochPublication(paths, expectedEpoch.epochId()); forceEpochPublication(paths, expectedEpoch.epochId(), history.packs.policy());
} }
migrateLegacyMantle(paths, history.activeActivation().activationId()); migrateLegacyMantle(paths, history.activeActivation().activationId());
if (!legacyExists) { if (!legacyExists) {
@@ -370,6 +385,75 @@ public final class GenerationHistory {
GenerationRegistryContract registryContract, GenerationRegistryContract registryContract,
int transitionWidthBlocks, int transitionWidthBlocks,
GenerationKernelRegistry.Version version 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 { ) throws IOException {
GenerationEpoch candidate = epoch( GenerationEpoch candidate = epoch(
packFingerprint, packFingerprint,
@@ -391,50 +475,54 @@ public final class GenerationHistory {
if (!store.activeEpoch().dimensionContract().hasSameLayout(candidate.dimensionContract())) { if (!store.activeEpoch().dimensionContract().hasSameLayout(candidate.dimensionContract())) {
throw new IllegalArgumentException("Generation update changes the immutable dimension contract."); 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(); Optional<GenerationActivation> pending = store.pendingActivation();
if (pending.isPresent()) { if (pending.isEmpty()) {
GenerationActivation activation = pending.get(); return Optional.empty();
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.get().epochId().equals(candidate.epochId())) {
if (store.activeEpoch().equals(candidate)) { throw new IllegalStateException("A different generation activation is already pending.");
requireSourceFingerprint(
packSource,
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
packs.requireExactPack(
candidate.epochId(),
candidate.packFingerprint(),
candidate.packFingerprintVersion()
);
return store.activeActivation();
} }
packs.requireExactPack(
requireSourceFingerprint( candidate.epochId(),
packSource,
candidate.packFingerprint(), candidate.packFingerprint(),
candidate.packFingerprintVersion() candidate.packFingerprintVersion()
); );
packs.publish( return pending;
}
private GenerationActivation requireActiveCandidate(GenerationEpoch candidate) throws IOException {
packs.requireExactPack(
candidate.epochId(), candidate.epochId(),
candidate.packFingerprint(), candidate.packFingerprint(),
candidate.packFingerprintVersion(), candidate.packFingerprintVersion()
packSource
); );
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); 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( GenerationActivation promotePending(
Collection<TerrainBoundarySignature> signatures Collection<TerrainBoundarySignature> signatures
) throws IOException { ) throws IOException {
@@ -1331,20 +1419,20 @@ public final class GenerationHistory {
private static void forceEpochPublication( private static void forceEpochPublication(
GenerationHistoryPaths paths, GenerationHistoryPaths paths,
String epochId String epochId,
EpochPolicy epochPolicy
) throws IOException { ) throws IOException {
Path epochRoot = paths.epochRoot(epochId); Path epochRoot = paths.epochRoot(epochId);
if (!Files.isDirectory(epochRoot, LinkOption.NOFOLLOW_LINKS) if (!Files.isDirectory(epochRoot, LinkOption.NOFOLLOW_LINKS)
|| Files.isSymbolicLink(epochRoot)) { || Files.isSymbolicLink(epochRoot)) {
throw new IOException("Generation epoch is not a safe directory: " + epochRoot); throw new IOException("Generation epoch is not a safe directory: " + epochRoot);
} }
if (File.separatorChar != '\\') { if (!epochPolicy.syncs() || File.separatorChar == '\\') {
if (Durability.enabled()) { return;
GenerationPackRepository.forceDirectoryTree(epochRoot, GenerationHistory::forceDirectory);
}
forceDirectory(paths.epochsRoot());
forceDirectory(paths.generationRoot());
} }
GenerationPackRepository.forceDirectoryTree(epochRoot, GenerationHistory::forceDirectory);
forceDirectory(paths.epochsRoot());
forceDirectory(paths.generationRoot());
} }
private static void forceDirectory(Path directory) throws IOException { private static void forceDirectory(Path directory) throws IOException {
@@ -1395,6 +1395,9 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable {
Path packRoot = history.packRoot(activation.activationId()); Path packRoot = history.packRoot(activation.activationId());
IrisData data = IrisData.openRuntime(packRoot.toFile()); IrisData data = IrisData.openRuntime(packRoot.toFile());
try { try {
if (epoch.packFingerprintVersion() == GenerationPackFingerprint.CURRENT_VERSION) {
data.useVerifiedGenerationPackFingerprint(epoch.packFingerprint());
}
data.bindGenerationRegistryContract(epoch.registryContract()); data.bindGenerationRegistryContract(epoch.registryContract());
IrisDimension dimension = data.getDimensionLoader().load(epoch.dimensionContract().dimensionKey()); IrisDimension dimension = data.getDimensionLoader().load(epoch.dimensionContract().dimensionKey());
if (dimension == null) { if (dimension == null) {
@@ -48,7 +48,11 @@ public final class GenerationHistoryStore {
private final Path generationDirectory; private final Path generationDirectory;
private final Path manifestPath; private final Path manifestPath;
private final Clock clock; private final Clock clock;
private static final DirectorySync NO_DIRECTORY_SYNC = directory -> {
};
private final DirectorySync directorySync; private final DirectorySync directorySync;
private final EpochPolicy policy;
private GenerationManifest manifest; private GenerationManifest manifest;
private IOException failure; private IOException failure;
@@ -56,20 +60,34 @@ public final class GenerationHistoryStore {
Path generationDirectory, Path generationDirectory,
GenerationManifest manifest, GenerationManifest manifest,
Clock clock, Clock clock,
DirectorySync directorySync DirectorySync directorySync,
EpochPolicy policy
) { ) {
this.generationDirectory = generationDirectory; this.generationDirectory = generationDirectory;
this.manifestPath = generationDirectory.resolve(MANIFEST_FILE_NAME); this.manifestPath = generationDirectory.resolve(MANIFEST_FILE_NAME);
this.manifest = Objects.requireNonNull(manifest, "manifest"); this.manifest = Objects.requireNonNull(manifest, "manifest");
this.clock = Objects.requireNonNull(clock, "clock"); this.clock = Objects.requireNonNull(clock, "clock");
this.directorySync = Objects.requireNonNull(directorySync, "directorySync"); this.directorySync = Objects.requireNonNull(directorySync, "directorySync");
this.policy = Objects.requireNonNull(policy, "policy");
} }
public static GenerationHistoryStore initialize( public static GenerationHistoryStore initialize(
Path generationDirectory, Path generationDirectory,
GenerationEpoch initialEpoch GenerationEpoch initialEpoch
) throws IOException { ) 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( static GenerationHistoryStore initialize(
@@ -85,6 +103,16 @@ public final class GenerationHistoryStore {
GenerationEpoch initialEpoch, GenerationEpoch initialEpoch,
Clock clock, Clock clock,
DirectorySync directorySync 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 { ) throws IOException {
Path directory = normalizeDirectory(generationDirectory); Path directory = normalizeDirectory(generationDirectory);
requireSafeParent(directory); requireSafeParent(directory);
@@ -92,7 +120,7 @@ public final class GenerationHistoryStore {
String lockName = "." + Objects.requireNonNull(directory.getFileName(), "Generation history directory name") String lockName = "." + Objects.requireNonNull(directory.getFileName(), "Generation history directory name")
+ ".manifest.lock"; + ".manifest.lock";
try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire(parent, lockName)) { try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire(parent, lockName)) {
ensureDirectory(directory); ensureDirectory(directory, policy);
Path manifestPath = directory.resolve(MANIFEST_FILE_NAME); Path manifestPath = directory.resolve(MANIFEST_FILE_NAME);
if (Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) {
throw new FileAlreadyExistsException(manifestPath.toString()); throw new FileAlreadyExistsException(manifestPath.toString());
@@ -103,16 +131,25 @@ public final class GenerationHistoryStore {
requiredClock.millis() requiredClock.millis()
); );
DirectorySync requiredDirectorySync = Objects.requireNonNull(directorySync, "directorySync"); DirectorySync requiredDirectorySync = Objects.requireNonNull(directorySync, "directorySync");
writeManifestAtomically(directory, manifestPath, manifest, null, false, requiredDirectorySync); writeManifestAtomically(directory, manifestPath, manifest, null, false, requiredDirectorySync, policy);
return new GenerationHistoryStore(directory, manifest, requiredClock, requiredDirectorySync); return new GenerationHistoryStore(directory, manifest, requiredClock, requiredDirectorySync, policy);
} }
} }
public static GenerationHistoryStore open(Path generationDirectory) throws IOException { 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 { 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); Path directory = normalizeDirectory(generationDirectory);
requireDirectory(directory); requireDirectory(directory);
Path manifestPath = directory.resolve(MANIFEST_FILE_NAME); Path manifestPath = directory.resolve(MANIFEST_FILE_NAME);
@@ -122,10 +159,15 @@ public final class GenerationHistoryStore {
directory, directory,
manifest, manifest,
clock, clock,
GenerationHistoryStore::forceDirectory manifestDirectorySync(policy),
policy
); );
} }
private static DirectorySync manifestDirectorySync(EpochPolicy policy) {
return policy.syncs() ? GenerationHistoryStore::forceDirectory : NO_DIRECTORY_SYNC;
}
public Path generationDirectory() { public Path generationDirectory() {
return generationDirectory; return generationDirectory;
} }
@@ -213,7 +255,7 @@ public final class GenerationHistoryStore {
private void writeUpdatedManifest(GenerationManifest updated) throws IOException { private void writeUpdatedManifest(GenerationManifest updated) throws IOException {
try { try {
writeManifestAtomically(generationDirectory, manifestPath, updated, manifest, true, directorySync); writeManifestAtomically(generationDirectory, manifestPath, updated, manifest, true, directorySync, policy);
} catch (IOException error) { } catch (IOException error) {
reconcileAfterWriteFailure(error); reconcileAfterWriteFailure(error);
throw error; throw error;
@@ -261,7 +303,8 @@ public final class GenerationHistoryStore {
GenerationManifest manifest, GenerationManifest manifest,
GenerationManifest previous, GenerationManifest previous,
boolean replaceExisting, boolean replaceExisting,
DirectorySync directorySync DirectorySync directorySync,
EpochPolicy policy
) throws IOException { ) throws IOException {
requireSafeParent(generationDirectory); requireSafeParent(generationDirectory);
requireDirectory(generationDirectory); requireDirectory(generationDirectory);
@@ -271,7 +314,7 @@ public final class GenerationHistoryStore {
} }
for (GenerationEpoch epoch : manifest.epochs()) { for (GenerationEpoch epoch : manifest.epochs()) {
if (previous == null || previous.epoch(epoch.epochId()).isEmpty()) { if (previous == null || previous.epoch(epoch.epochId()).isEmpty()) {
publishEpoch(generationDirectory, epoch); publishEpoch(generationDirectory, epoch, policy);
} }
} }
Path temporary = Files.createTempFile(generationDirectory, ".manifest-", ".tmp"); Path temporary = Files.createTempFile(generationDirectory, ".manifest-", ".tmp");
@@ -285,7 +328,7 @@ public final class GenerationHistoryStore {
while (buffer.hasRemaining()) { while (buffer.hasRemaining()) {
channel.write(buffer); channel.write(buffer);
} }
Durability.force(channel); forceFile(channel, policy);
} }
try { try {
if (replaceExisting) { 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"); Path epochsDirectory = generationDirectory.resolve("epochs");
ensureDirectory(epochsDirectory); ensureDirectory(epochsDirectory, policy);
Path epochDirectory = epochDirectory(generationDirectory, epoch.epochId()); Path epochDirectory = epochDirectory(generationDirectory, epoch.epochId());
ensureDirectory(epochDirectory); ensureDirectory(epochDirectory, policy);
Path metadata = epochDirectory.resolve("epoch.json"); Path metadata = epochDirectory.resolve("epoch.json");
if (Files.exists(metadata, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(metadata, LinkOption.NOFOLLOW_LINKS)) {
if (!readEpoch(generationDirectory, epoch.epochId()).equals(epoch)) { if (!readEpoch(generationDirectory, epoch.epochId()).equals(epoch)) {
@@ -355,14 +399,14 @@ public final class GenerationHistoryStore {
while (buffer.hasRemaining()) { while (buffer.hasRemaining()) {
channel.write(buffer); channel.write(buffer);
} }
Durability.force(channel); forceFile(channel, policy);
} }
try { try {
Files.move(temporary, metadata, StandardCopyOption.ATOMIC_MOVE); Files.move(temporary, metadata, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException exception) { } catch (AtomicMoveNotSupportedException exception) {
throw new IOException("Generation history requires atomic epoch publication.", exception); throw new IOException("Generation history requires atomic epoch publication.", exception);
} }
forceDirectory(epochDirectory); forceDirectory(epochDirectory, policy);
} finally { } finally {
Files.deleteIfExists(temporary); Files.deleteIfExists(temporary);
} }
@@ -379,24 +423,37 @@ public final class GenerationHistoryStore {
return Objects.requireNonNull(directory, "generationDirectory").toAbsolutePath().normalize(); 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); requireSafeParent(directory);
Path parent = Objects.requireNonNull(directory.getParent(), "Generation history parent");
if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
requireDirectory(directory); requireDirectory(directory);
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent")); forceDirectory(parent, policy);
return; return;
} }
try { try {
Files.createDirectory(directory); Files.createDirectory(directory);
} catch (FileAlreadyExistsException race) { } catch (FileAlreadyExistsException race) {
requireDirectory(directory); requireDirectory(directory);
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent")); forceDirectory(parent, policy);
return; return;
} }
forceDirectory(Objects.requireNonNull(directory.getParent(), "Generation history parent")); forceDirectory(parent, policy);
requireDirectory(directory); 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 { private static void requireDirectory(Path directory) throws IOException {
requireSafeParent(directory); requireSafeParent(directory);
if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) {
@@ -19,11 +19,15 @@ import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveAction;
@@ -39,14 +43,25 @@ public final class GenerationPackRepository {
private final Path dimensionRoot; private final Path dimensionRoot;
private final Path generationRoot; private final Path generationRoot;
private final Path epochsRoot; private final Path epochsRoot;
private final EpochPolicy policy;
private final Set<String> verifiedPacks = ConcurrentHashMap.newKeySet();
public GenerationPackRepository(Path dimensionRoot) { public GenerationPackRepository(Path dimensionRoot) {
this(dimensionRoot, EpochPolicy.configured());
}
public GenerationPackRepository(Path dimensionRoot, EpochPolicy policy) {
Path root = Objects.requireNonNull(dimensionRoot, "dimensionRoot") Path root = Objects.requireNonNull(dimensionRoot, "dimensionRoot")
.toAbsolutePath() .toAbsolutePath()
.normalize(); .normalize();
this.dimensionRoot = root; this.dimensionRoot = root;
generationRoot = root.resolve("iris").resolve("generation"); generationRoot = root.resolve("iris").resolve("generation");
epochsRoot = generationRoot.resolve("epochs"); epochsRoot = generationRoot.resolve("epochs");
this.policy = Objects.requireNonNull(policy, "policy");
}
public EpochPolicy policy() {
return policy;
} }
public Path generationRoot() { public Path generationRoot() {
@@ -61,11 +76,26 @@ public final class GenerationPackRepository {
return epochRoot(epochId).resolve("pack"); return epochRoot(epochId).resolve("pack");
} }
public synchronized Path publish( public Path publish(
String epochId, String epochId,
String packFingerprint, String packFingerprint,
int packFingerprintVersion, int packFingerprintVersion,
Path source 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 { ) throws IOException {
String requiredEpochId = requireDigest(epochId, "epochId"); String requiredEpochId = requireDigest(epochId, "epochId");
String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint"); String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
@@ -75,7 +105,7 @@ public final class GenerationPackRepository {
".epoch-" + requiredEpochId + ".lock" ".epoch-" + requiredEpochId + ".lock"
)) { )) {
ensureEpochsRoot(); 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 epochId,
String packFingerprint, String packFingerprint,
int packFingerprintVersion, int packFingerprintVersion,
Path source Path source,
Path basisPack
) throws IOException { ) throws IOException {
Path epochDirectory = ensureChildDirectory(epochsRoot, epochId); Path epochDirectory = ensureChildDirectory(epochsRoot, epochId);
Path target = epochDirectory.resolve("pack"); Path target = epochDirectory.resolve("pack");
@@ -94,39 +125,102 @@ public final class GenerationPackRepository {
Path stage = Files.createTempDirectory(epochDirectory, ".pack-"); Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
try { try {
Files.delete(stage); Files.delete(stage);
copyPackTree(source, stage); copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), publicationCopyMode(), basisPack, null);
requireFingerprint(stage, packFingerprint, packFingerprintVersion); requireFingerprint(stage, packFingerprint, packFingerprintVersion);
try (AtomicDirectoryPublisher.Publication publication = return commitStage(epochId, stage, packFingerprint, packFingerprintVersion);
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;
} finally { } finally {
if (Files.exists(stage, LinkOption.NOFOLLOW_LINKS)) { deleteLeftoverStage(stage);
AtomicDirectoryPublisher.deleteTree(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( public Path requireExactPack(
String epochId, String epochId,
String packFingerprint, String packFingerprint,
int packFingerprintVersion int packFingerprintVersion
) throws IOException { ) throws IOException {
Path pack = requireSafePackRoot(epochId); Path pack = requireSafePackRoot(epochId);
requireFingerprint( String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
pack, if (policy.trustsVerifiedPacks()
requireDigest(packFingerprint, "packFingerprint"), && verifiedPacks.contains(verifiedPackKey(epochId, requiredFingerprint, packFingerprintVersion))) {
packFingerprintVersion return pack;
); }
requireFingerprint(pack, requiredFingerprint, packFingerprintVersion);
rememberVerifiedPack(epochId, requiredFingerprint, packFingerprintVersion);
return pack; 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 { Path requireSafePackRoot(String epochId) throws IOException {
String requiredEpochId = requireDigest(epochId, "epochId"); String requiredEpochId = requireDigest(epochId, "epochId");
validateExistingAncestors(requiredEpochId); validateExistingAncestors(requiredEpochId);
@@ -157,21 +251,25 @@ public final class GenerationPackRepository {
requireSafeDirectory(epoch, "Generation epoch path is not a safe directory"); 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); Path child = parent.resolve(name);
if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) {
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory"); requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
forceDirectory(parent); syncDirectory(parent);
return child; return child;
} }
try { try {
Files.createDirectory(child); Files.createDirectory(child);
} catch (FileAlreadyExistsException race) { } catch (FileAlreadyExistsException race) {
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory"); requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
forceDirectory(parent); syncDirectory(parent);
return child; return child;
} }
forceDirectory(parent); syncDirectory(parent);
requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory"); requireSafeDirectory(child, "Generation epoch ancestor is not a safe directory");
return child; return child;
} }
@@ -190,8 +288,8 @@ public final class GenerationPackRepository {
} }
} }
private static void forceDirectory(Path directory) throws IOException { private void syncDirectory(Path directory) throws IOException {
if (File.separatorChar == '\\') { if (!policy.syncs() || File.separatorChar == '\\') {
return; return;
} }
try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { 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 { public static void copyPackTree(Path source, Path target) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool(); copyPackTree(source, target, defaultExecutor(), defaultWorkers());
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors())); }
copyPackTree(source, target, executor, workers);
/**
* 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 { 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"); Objects.requireNonNull(executor, "executor");
if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) { if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) {
throw new IllegalArgumentException("Pack copy workers must be between 1 and " + 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(); Path normalizedSource = requirePackSource(source);
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 normalizedTarget = Objects.requireNonNull(target, "target").toAbsolutePath().normalize(); Path normalizedTarget = Objects.requireNonNull(target, "target").toAbsolutePath().normalize();
if (Files.exists(normalizedTarget, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(normalizedTarget)) { if (Files.exists(normalizedTarget, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(normalizedTarget)) {
throw new IOException("Pack publication stage already exists: " + normalizedTarget); throw new IOException("Pack publication stage already exists: " + normalizedTarget);
@@ -229,7 +339,45 @@ public final class GenerationPackRepository {
+ normalizedSource + " and " + normalizedTarget); + 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<>() { Files.walkFileTree(normalizedSource, new SimpleFileVisitor<>() {
@Override @Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException { public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
@@ -241,7 +389,7 @@ public final class GenerationPackRepository {
&& PackDirectoryResolver.isHiddenName(directory.getFileName().toString())) { && PackDirectoryResolver.isHiddenName(directory.getFileName().toString())) {
return FileVisitResult.SKIP_SUBTREE; return FileVisitResult.SKIP_SUBTREE;
} }
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory)); includedDirectory.run(directory);
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
@@ -259,7 +407,7 @@ public final class GenerationPackRepository {
|| fileName.endsWith(".code-workspace")) { || fileName.endsWith(".code-workspace")) {
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
sourceFiles.add(file); files.put(relative, new PackTreeState.FileStamp(attributes.size(), attributes.lastModifiedTime()));
return FileVisitResult.CONTINUE; return FileVisitResult.CONTINUE;
} }
@@ -268,17 +416,42 @@ public final class GenerationPackRepository {
throw new IOException("Unable to copy pack entry: " + file, failure); throw new IOException("Unable to copy pack entry: " + file, failure);
} }
}); });
executeFilePhase(sourceFiles, executor, workers, sourceFile -> return new PackTreeState(files);
Files.copy(sourceFile, copyDestination(normalizedSource, normalizedTarget, sourceFile), }
StandardCopyOption.COPY_ATTRIBUTES));
executeFilePhase(sourceFiles, executor, workers, sourceFile -> private static boolean linkUnchangedFile(
forceFile(copyDestination(normalizedSource, normalizedTarget, sourceFile))); 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 { static void forceDirectoryTree(Path root, FileAction force) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool(); forceDirectoryTree(root, defaultExecutor(), defaultWorkers(), force);
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
forceDirectoryTree(root, executor, workers, force);
} }
static void forceDirectoryTree(Path root, Executor executor, int workers, FileAction force) throws IOException { static void forceDirectoryTree(Path root, Executor executor, int workers, FileAction force) throws IOException {
@@ -396,11 +569,21 @@ public final class GenerationPackRepository {
return requiredValue; return requiredValue;
} }
enum PackCopyMode {
DURABLE,
SCRATCH
}
@FunctionalInterface @FunctionalInterface
interface FileAction { interface FileAction {
void run(Path file) throws IOException; 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) { 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); ReferencedPlatformKeys referenced = referencedPlatformKeys(packRoot, requiredRegistries);
addPlatformDefinitions(definitions, BLOCK_REGISTRY, referenced.blockKeys(), requiredGenerationRegistry); addPlatformDefinitions(definitions, BLOCK_REGISTRY, referenced.blockKeys(), requiredGenerationRegistry);
addPlatformDefinitions(definitions, ENTITY_TYPE_REGISTRY, referenced.entityKeys(), requiredGenerationRegistry); addPlatformDefinitions(definitions, ENTITY_TYPE_REGISTRY, referenced.entityKeys(), requiredGenerationRegistry);
GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry) GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry).withBiomeTags(biomeTags)
.withBiomeTags(biomeTags)
.withCustomBiomeStandIns(customBiomeStandIns); .withCustomBiomeStandIns(customBiomeStandIns);
String actualPackFingerprint = GenerationPackFingerprint.compute( if (!requiredPackFingerprint.equals(packFingerprintAfterCapture(requiredData, packRoot))) {
packRoot,
GenerationPackFingerprint.CURRENT_VERSION
);
if (!requiredPackFingerprint.equals(actualPackFingerprint)) {
throw new IOException("Iris generation registry capture rejected a changed pack."); throw new IOException("Iris generation registry capture rejected a changed pack.");
} }
return captured; 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( public static CustomBiomeDefinition customBiomeDefinition(
IrisData data, IrisData data,
IrisDimension dimension, 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. # {befb} Formatierter Teil einer Engine-Zeitmessungsbezeichnung vor dem Klammerteil.
# {before} Wert vor der Änderung oder unerreichbare Baumblöcke vor der Reparatur. # {before} Wert vor der Änderung oder unerreichbare Baumblöcke vor der Reparatur.
# {biome} Name oder Kennung des angezeigten Bioms. # {biome} Name oder Kennung des angezeigten Bioms.
# {biomes} Biome, deren Änderungen erst nach einem Serverneustart gelten.
# {block} Typ oder Beschreibung des untersuchten Blocks. # {block} Typ oder Beschreibung des untersuchten Blocks.
# {blockX} X-Koordinate des Blocks oder Teleportationsziels. # {blockX} X-Koordinate des Blocks oder Teleportationsziels.
# {blockY} Y-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. # {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. # {before} Valor anterior al cambio o bloques del árbol inaccesibles antes de repararlo.
# {biome} Nombre o identificador del bioma mostrado. # {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. # {block} Tipo o descripción del bloque inspeccionado.
# {blockX} Coordenada X del bloque o del destino de teletransporte. # {blockX} Coordenada X del bloque o del destino de teletransporte.
# {blockY} Coordenada Y 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. # {befb} Moottorin ajoitusotsikon muotoiltu osa ennen hakasulkuosaa.
# {before} Arvo ennen muutosta tai saavuttamattomat puulohkot ennen korjausta. # {before} Arvo ennen muutosta tai saavuttamattomat puulohkot ennen korjausta.
# {biome} Näytettävän biomin nimi tai tunniste. # {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. # {block} Tarkasteltavan lohkon tyyppi tai kuvaus.
# {blockX} Lohkon tai teleporttikohteen X-koordinaatti. # {blockX} Lohkon tai teleporttikohteen X-koordinaatti.
# {blockY} Lohkon tai teleporttikohteen Y-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. # {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. # {before} Valeur avant modification ou blocs d’arbre inaccessibles avant réparation.
# {biome} Nom ou identifiant du biome affiché. # {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é. # {block} Type ou description du bloc inspecté.
# {blockX} Coordonnée X du bloc ou de la destination de téléportation. # {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. # {blockY} Coordonnée Y du bloc ou de la destination de téléportation.
@@ -55,6 +55,7 @@
# {befb} החלק המעוצב בתווית זמני המנוע שלפני הסוגריים המרובעים. # {befb} החלק המעוצב בתווית זמני המנוע שלפני הסוגריים המרובעים.
# {before} הערך לפני השינוי, או בלוקי העץ הבלתי נגישים לפני תיקון. # {before} הערך לפני השינוי, או בלוקי העץ הבלתי נגישים לפני תיקון.
# {biome} שם הביומה או המזהה שלה. # {biome} שם הביומה או המזהה שלה.
# {biomes} ביומים שהשינויים בהם יחולו רק לאחר הפעלה מחדש של השרת.
# {block} סוג הבלוק הנבדק או תיאורו. # {block} סוג הבלוק הנבדק או תיאורו.
# {blockX} קואורדינטת X של הבלוק או יעד השיגור. # {blockX} קואורדינטת X של הבלוק או יעד השיגור.
# {blockY} קואורדינטת Y של הבלוק או יעד השיגור. # {blockY} קואורדינטת Y של הבלוק או יעד השיגור.
@@ -50,6 +50,7 @@
# {befb} Parte formattata di un’etichetta dei tempi del motore prima della porzione tra parentesi quadre. # {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. # {before} Valore prima della modifica o blocchi dell’albero irraggiungibili prima della riparazione.
# {biome} Nome o identificatore del bioma visualizzato. # {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. # {block} Tipo o descrizione del blocco esaminato.
# {blockX} Coordinata X del blocco o della destinazione del teletrasporto. # {blockX} Coordinata X del blocco o della destinazione del teletrasporto.
# {blockY} Coordinata Y del blocco o della destinazione del teletrasporto. # {blockY} Coordinata Y del blocco o della destinazione del teletrasporto.
@@ -53,6 +53,7 @@
# {befb} エンジン処理時間ラベルの括弧部分より前にある書式付きテキスト。 # {befb} エンジン処理時間ラベルの括弧部分より前にある書式付きテキスト。
# {before} 変更前の値、または修復前に接続されていなかった木のブロック数。 # {before} 変更前の値、または修復前に接続されていなかった木のブロック数。
# {biome} 表示中のバイオームの名前または識別子。 # {biome} 表示中のバイオームの名前または識別子。
# {biomes} サーバーの再起動後にのみ変更が反映されるバイオーム。
# {block} 調べているブロックの種類または説明。 # {block} 調べているブロックの種類または説明。
# {blockX} ブロックまたはテレポート先の X 座標。 # {blockX} ブロックまたはテレポート先の X 座標。
# {blockY} ブロックまたはテレポート先の Y 座標。 # {blockY} ブロックまたはテレポート先の Y 座標。
@@ -53,6 +53,7 @@
# {befb} 엔진 처리 시간 라벨에서 괄호 앞에 오는 서식 지정 텍스트. # {befb} 엔진 처리 시간 라벨에서 괄호 앞에 오는 서식 지정 텍스트.
# {before} 변경 전 값 또는 수리 전에 연결되지 않았던 나무 블록 수. # {before} 변경 전 값 또는 수리 전에 연결되지 않았던 나무 블록 수.
# {biome} 표시 중인 생물 군계의 이름 또는 식별자. # {biome} 표시 중인 생물 군계의 이름 또는 식별자.
# {biomes} 서버를 재시작해야 변경 사항이 적용되는 생물 군계.
# {block} 조사 중인 블록의 종류 또는 설명. # {block} 조사 중인 블록의 종류 또는 설명.
# {blockX} 블록 또는 순간 이동 목적지의 X 좌표. # {blockX} 블록 또는 순간 이동 목적지의 X 좌표.
# {blockY} 블록 또는 순간 이동 목적지의 Y 좌표. # {blockY} 블록 또는 순간 이동 목적지의 Y 좌표.
@@ -55,6 +55,7 @@
# {befb} Suformatuota variklio laiko žymos dalis prieš laužtinius skliaustus. # {befb} Suformatuota variklio laiko žymos dalis prieš laužtinius skliaustus.
# {before} Reikšmė prieš pakeitimą arba nepasiekiami medžio blokai prieš taisymą. # {before} Reikšmė prieš pakeitimą arba nepasiekiami medžio blokai prieš taisymą.
# {biome} Rodomo biomo pavadinimas arba identifikatorius. # {biome} Rodomo biomo pavadinimas arba identifikatorius.
# {biomes} Biomai, kurių pakeitimai įsigalioja tik paleidus serverį iš naujo.
# {block} Tikrinamo bloko tipas arba aprašymas. # {block} Tikrinamo bloko tipas arba aprašymas.
# {blockX} Bloko arba teleportacijos vietos X koordinatė. # {blockX} Bloko arba teleportacijos vietos X koordinatė.
# {blockY} Bloko arba teleportacijos vietos Y 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. # {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. # {before} Waarde vóór de wijziging, of onbereikbare boomblokken vóór reparatie.
# {biome} Naam of identificatie van het getoonde bioom. # {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. # {block} Type of beschrijving van het onderzochte blok.
# {blockX} X-coördinaat van het blok of de teleportbestemming. # {blockX} X-coördinaat van het blok of de teleportbestemming.
# {blockY} Y-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. # {befb} Sformatowana część etykiety czasu silnika przed fragmentem w nawiasach kwadratowych.
# {before} Wartość przed zmianą albo niedostępne bloki drzewa przed naprawą. # {before} Wartość przed zmianą albo niedostępne bloki drzewa przed naprawą.
# {biome} Nazwa lub identyfikator wyświetlanego biomu. # {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. # {block} Typ lub opis sprawdzanego bloku.
# {blockX} Współrzędna X bloku lub celu teleportacji. # {blockX} Współrzędna X bloku lub celu teleportacji.
# {blockY} Współrzędna Y 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. # {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. # {before} Valor anterior à alteração ou blocos de árvore inacessíveis antes da reparação.
# {biome} Nome ou identificador do bioma apresentado. # {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. # {block} Tipo ou descrição do bloco inspecionado.
# {blockX} Coordenada X do bloco ou do destino de teletransporte. # {blockX} Coordenada X do bloco ou do destino de teletransporte.
# {blockY} Coordenada Y do bloco ou do destino de teletransporte. # {blockY} Coordenada Y do bloco ou do destino de teletransporte.
@@ -55,6 +55,7 @@
# {befb} Оформленная часть метки времени движка перед фрагментом в квадратных скобках. # {befb} Оформленная часть метки времени движка перед фрагментом в квадратных скобках.
# {before} Значение до изменения либо недоступные блоки дерева до исправления. # {before} Значение до изменения либо недоступные блоки дерева до исправления.
# {biome} Имя или идентификатор отображаемого биома. # {biome} Имя или идентификатор отображаемого биома.
# {biomes} Биомы, изменения которых применяются только после перезапуска сервера.
# {block} Тип или описание проверяемого блока. # {block} Тип или описание проверяемого блока.
# {blockX} Координата X блока или точки телепортации. # {blockX} Координата X блока или точки телепортации.
# {blockY} Координата Y блока или точки телепортации. # {blockY} Координата Y блока или точки телепортации.
@@ -55,6 +55,7 @@
# {befb} Motor zamanlama etiketinin köşeli parantezli bölümünden önceki biçimlendirilmiş kısmı. # {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ı. # {before} Değişiklikten önceki değer veya onarım öncesi erişilemeyen ağaç blokları.
# {biome} Gösterilen biyomun adı veya kimliği. # {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ı. # {block} İncelenen bloğun türü veya açıklaması.
# {blockX} Bloğun veya ışınlanma hedefinin X koordinatı. # {blockX} Bloğun veya ışınlanma hedefinin X koordinatı.
# {blockY} Bloğun veya ışınlanma hedefinin Y 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ý. # {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. # {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ị. # {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. # {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. # {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. # {blockY} Tọa độ Y của khối hoặc điểm dịch chuyển.
@@ -53,6 +53,7 @@
# {befb} 引擎耗时标签中括号部分之前的已格式化文本。 # {befb} 引擎耗时标签中括号部分之前的已格式化文本。
# {before} 更改前的值,或修复前无法连通的树木方块数。 # {before} 更改前的值,或修复前无法连通的树木方块数。
# {biome} 正在显示的生物群系名称或标识符。 # {biome} 正在显示的生物群系名称或标识符。
# {biomes} 其更改仅在服务器重启后生效的生物群系。
# {block} 正在检查的方块类型或描述。 # {block} 正在检查的方块类型或描述。
# {blockX} 方块或传送目的地的 X 坐标。 # {blockX} 方块或传送目的地的 X 坐标。
# {blockY} 方块或传送目的地的 Y 坐标。 # {blockY} 方块或传送目的地的 Y 坐标。
@@ -53,6 +53,7 @@
# {befb} 引擎耗時標籤中括號部分之前的已格式化文字。 # {befb} 引擎耗時標籤中括號部分之前的已格式化文字。
# {before} 變更前的值,或修復前無法連通的樹木方塊數。 # {before} 變更前的值,或修復前無法連通的樹木方塊數。
# {biome} 正在顯示的生態域名稱或識別碼。 # {biome} 正在顯示的生態域名稱或識別碼。
# {biomes} 其變更僅在伺服器重新啟動後生效的生態域。
# {block} 正在檢查的方塊類型或描述。 # {block} 正在檢查的方塊類型或描述。
# {blockX} 方塊或傳送目的地的 X 座標。 # {blockX} 方塊或傳送目的地的 X 座標。
# {blockY} 方塊或傳送目的地的 Y 座標。 # {blockY} 方塊或傳送目的地的 Y 座標。
@@ -84,6 +84,16 @@ public class IrisSettingsDefaultsTest {
assertEquals(256, changed.getGenerator().getGenerationTransitionWidthBlocks()); 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 @Test
public void hotloadSnapshotIsValidatedBeforeReplacingLiveSettings() { public void hotloadSnapshotIsValidatedBeforeReplacingLiveSettings() {
IrisSettings previous = IrisSettings.settings; IrisSettings previous = IrisSettings.settings;
@@ -138,7 +138,7 @@ public class EngineHotloaderRecoveryTest {
try (MockedStatic<StudioGenerationUpdate> updates = mockStatic(StudioGenerationUpdate.class); try (MockedStatic<StudioGenerationUpdate> updates = mockStatic(StudioGenerationUpdate.class);
MockedStatic<IrisBoundarySignatureSampler> signatures = mockStatic(IrisBoundarySignatureSampler.class); MockedStatic<IrisBoundarySignatureSampler> signatures = mockStatic(IrisBoundarySignatureSampler.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.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); configuration.when(IrisSettings::get).thenReturn(settings);
IllegalStateException thrown = assertThrows(IllegalStateException.class, 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.IrisStructureLocator;
import art.arcane.iris.structure.placement.StructureReachability; import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.world.IrisWorld; 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.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
import art.arcane.iris.world.history.IrisBoundarySignatureSampler; import art.arcane.iris.world.history.IrisBoundarySignatureSampler;
@@ -66,7 +67,7 @@ public class EngineHotloaderRetirementTest {
} }
}); });
planning.get(5L, TimeUnit.SECONDS); planning.get(5L, TimeUnit.SECONDS);
return null; return mock(GenerationActivation.class);
}).when(cutover).promotePending(); }).when(cutover).promotePending();
StudioGenerationUpdate update = mock(StudioGenerationUpdate.class); StudioGenerationUpdate update = mock(StudioGenerationUpdate.class);
IrisSettings settings = mock(IrisSettings.class, RETURNS_DEEP_STUBS); IrisSettings settings = mock(IrisSettings.class, RETURNS_DEEP_STUBS);
@@ -76,7 +77,7 @@ public class EngineHotloaderRetirementTest {
MockedStatic<IrisStructureLocator> structures = mockStatic(IrisStructureLocator.class); MockedStatic<IrisStructureLocator> structures = mockStatic(IrisStructureLocator.class);
MockedStatic<StructureReachability> reachability = mockStatic(StructureReachability.class); MockedStatic<StructureReachability> reachability = mockStatic(StructureReachability.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.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); configuration.when(IrisSettings::get).thenReturn(settings);
new EngineHotloader(engine).hotloadSilently(); 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.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryPaths; import art.arcane.iris.world.history.GenerationHistoryPaths;
import art.arcane.iris.world.history.GenerationPackFingerprint; import art.arcane.iris.world.history.GenerationPackFingerprint;
import art.arcane.iris.world.history.PackTreeState;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
@@ -15,6 +16,7 @@ import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -30,45 +32,80 @@ public final class StudioGenerationUpdateTest {
public final TemporaryFolder temporary = new TemporaryFolder(); public final TemporaryFolder temporary = new TemporaryFolder();
@Test @Test
public void unchangedSourceNeedsNoSnapshotOrManifestUpdate() throws Exception { public void unchangedSourceNeedsNoManifestUpdateAndLeavesNoSnapshot() throws Exception {
Path source = temporary.newFolder("unchanged-pack").toPath(); Path source = temporary.newFolder("unchanged-pack").toPath();
Files.createDirectories(source.resolve("dimensions")); Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}"); 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); IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class); GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class); GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(source); when(engine.getStudioGenerationSource()).thenReturn(source);
when(history.activeEpoch()).thenReturn(active); when(history.activeEpoch()).thenReturn(active);
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION); when(active.epochId()).thenReturn("a".repeat(64));
when(active.packFingerprint()).thenReturn(fingerprint); 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(); verify(history).activeEpoch();
verifyNoMoreInteractions(history); verifyNoMoreInteractions(history);
} }
@Test @Test
public void unchangedAuthoringRootAliasNeedsNoSnapshot() throws Exception { public void recordOfAnotherEpochIsIgnored() throws Exception {
Path source = temporary.newFolder("unchanged-alias-target").toPath(); Path source = temporary.newFolder("stale-record-pack").toPath();
Files.createDirectories(source.resolve("dimensions")); Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}"); Files.writeString(source.resolve("dimensions/test.json"), "{}");
Path alias = temporary.getRoot().toPath().resolve("unchanged-alias"); GenerationEpoch active = mock(GenerationEpoch.class);
Files.createSymbolicLink(alias, source); 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); 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); IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class); GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class); GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(alias); when(engine.getStudioGenerationSource()).thenReturn(authoringRoot);
when(history.activeEpoch()).thenReturn(active); when(history.activeEpoch()).thenReturn(active);
when(history.paths()).thenReturn(paths);
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION); when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn(fingerprint); 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).activeEpoch();
verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history); verifyNoMoreInteractions(history);
} }
@@ -91,7 +128,7 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION); when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64)); 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( assertTrue(failure.getMessage(), failure.getMessage().contains(
"Studio pack update is invalid: Dimension 'test' declares no regions.")); "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, times(2)).activeEpoch();
verify(history).paths(); verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history); verifyNoMoreInteractions(history);
} }
@@ -117,13 +155,36 @@ public final class StudioGenerationUpdateTest {
when(engine.getStudioGenerationSource()).thenReturn(alias); when(engine.getStudioGenerationSource()).thenReturn(alias);
GenerationHistory history = mock(GenerationHistory.class); 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); 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 @Test
public void invalidPackLeavesManifestUntouchedAndRemovesItsTemporarySnapshot() throws Exception { public void invalidPackLeavesManifestUntouchedAndRemovesItsTemporarySnapshot() throws Exception {
Path source = temporary.newFolder("invalid-pack").toPath(); Path source = temporary.newFolder("invalid-pack").toPath();
@@ -141,15 +202,16 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION); when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64)); 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())); assertEquals("unchanged manifest", Files.readString(paths.manifest()));
try (Stream<Path> entries = Files.list(paths.generationRoot())) { try (Stream<Path> entries = Files.list(paths.generationRoot())) {
assertEquals(1L, entries.count()); assertEquals(1L, entries.count());
} }
verify(history, times(2)).activeEpoch(); verify(history, times(2)).activeEpoch();
verify(history).paths(); verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history); verifyNoMoreInteractions(history);
} }
@@ -174,7 +236,7 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION); when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn("0".repeat(64)); 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( assertTrue(failure.getMessage(), failure.getMessage().contains(
"Dimension 'test' structures[0].anchor must be omitted, null, or LEGACY for nativeStructures.")); "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, times(2)).activeEpoch();
verify(history).paths(); verify(history).paths();
verify(history).activePackLinkBasis();
verifyNoMoreInteractions(history); 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.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.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.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.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.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)"), 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; package art.arcane.iris.world.history;
import art.arcane.iris.testsupport.DurabilityMode; import art.arcane.iris.testsupport.DurabilityMode;
import art.arcane.iris.world.storage.Durability;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import org.junit.Assume; import org.junit.Assume;
@@ -43,6 +44,30 @@ public class GenerationHistoryStoreTest {
@Rule @Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(); 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 @Test
public void persistsActiveAndPendingHistoryAcrossReopen() throws Exception { public void persistsActiveAndPendingHistoryAcrossReopen() throws Exception {
Path directory = temporaryFolder.getRoot().toPath().resolve("generation"); Path directory = temporaryFolder.getRoot().toPath().resolve("generation");
@@ -1,5 +1,7 @@
package art.arcane.iris.world.history; package art.arcane.iris.world.history;
import art.arcane.iris.world.storage.Durability;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; 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 @Test
public void firstPackAccessRejectsTamperingAfterCreation() throws Exception { public void firstPackAccessRejectsTamperingAfterCreation() throws Exception {
Path world = temporaryFolder.newFolder("tampered-publication-world").toPath(); Path world = temporaryFolder.newFolder("tampered-publication-world").toPath();
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history; package art.arcane.iris.world.history;
import art.arcane.iris.world.storage.Durability;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@@ -9,11 +10,13 @@ import org.mockito.MockedStatic;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CyclicBarrier; import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; 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 @Test
public void rejectsMutationOfAnExistingEpoch() throws Exception { public void rejectsMutationOfAnExistingEpoch() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath(); Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath();