mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 08:44:50 +00:00
Hash studio pack edits once
- Replace EpochDurability with EpochPolicy, whose studio mode also trusts packs the history already hashed itself - Snapshot studio edits once into the generation folder, hard-linking files unchanged from the active epoch - Hash the snapshot once and move it into the epoch repository instead of copying and hashing it again - Detect source edits during the snapshot by comparing file sizes and modification times before and after - Keep copy, sync and re-hash for durable histories, which cannot adopt unsynced trees
This commit is contained in:
1 parent
726c066c8d
commit
6ec3acdf64
13 files changed
+552
-177
No files matched your search
@@ -260,7 +260,7 @@ final class EngineHotloader {
|
||||
IrisSettings settings = IrisSettings.get();
|
||||
int transitionWidth = settings.getStudio().isBlendChanges()
|
||||
? settings.getGenerator().getGenerationTransitionWidthBlocks() : 0;
|
||||
history.stageUpdate(update.source(), update.fingerprint(), update.dimensionContract(),
|
||||
history.stageVerifiedUpdate(update.pack(), update.dimensionContract(),
|
||||
update.registryContract(), transitionWidth);
|
||||
}
|
||||
long stagedAt = System.nanoTime();
|
||||
|
||||
@@ -5,10 +5,11 @@ import art.arcane.iris.pack.AtomicDirectoryPublisher;
|
||||
import art.arcane.iris.world.history.GenerationEpoch;
|
||||
import art.arcane.iris.world.history.GenerationEpochContractFactory;
|
||||
import art.arcane.iris.world.history.GenerationHistory;
|
||||
import art.arcane.iris.world.history.GenerationPackFingerprint;
|
||||
import art.arcane.iris.world.history.GenerationPackRepository;
|
||||
import art.arcane.iris.world.history.GenerationRegistryContract;
|
||||
import art.arcane.iris.world.history.GenerationRegistryContractFactory;
|
||||
import art.arcane.iris.world.history.PackTreeState;
|
||||
import art.arcane.iris.world.history.VerifiedPackTree;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -16,32 +17,30 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A Studio pack edit captured as one read-only snapshot inside the world's generation folder. The snapshot is
|
||||
* hashed once and later moved into the epoch repository as it is.
|
||||
*/
|
||||
record StudioGenerationUpdate(
|
||||
Path stagingRoot,
|
||||
Path source,
|
||||
String fingerprint,
|
||||
VerifiedPackTree pack,
|
||||
PackTreeState sourceState,
|
||||
GenerationEpoch.DimensionContract dimensionContract,
|
||||
GenerationRegistryContract registryContract
|
||||
) implements AutoCloseable {
|
||||
private static final String TRIAL_MANTLE_DIRECTORY = "trial-mantle";
|
||||
private static final String TRIAL_MANTLE_DIRECTORY = ".trial-mantle";
|
||||
|
||||
static StudioGenerationUpdate prepare(IrisEngine engine, GenerationHistory history) throws IOException {
|
||||
Path source = engine.getStudioGenerationSource().toRealPath();
|
||||
IrisData.invalidateLoadedAuthoringResources(source.toFile());
|
||||
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
|
||||
GenerationEpoch active = history.activeEpoch();
|
||||
if (active.packFingerprintVersion() == GenerationPackFingerprint.CURRENT_VERSION
|
||||
&& fingerprint.equals(active.packFingerprint())) {
|
||||
return null;
|
||||
}
|
||||
PackTreeState sourceState = PackTreeState.capture(source);
|
||||
Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-");
|
||||
Path snapshot = stagingRoot.resolve(source.getFileName());
|
||||
try {
|
||||
GenerationPackRepository.snapshotPackTree(source, snapshot);
|
||||
if (!fingerprint.equals(GenerationPackFingerprint.compute(snapshot, GenerationPackFingerprint.CURRENT_VERSION))) {
|
||||
throw new IOException("Studio pack changed while its update snapshot was being captured.");
|
||||
StudioGenerationUpdate update = prepareStaged(engine, history, source, sourceState, stagingRoot);
|
||||
if (update == null) {
|
||||
AtomicDirectoryPublisher.deleteTree(stagingRoot);
|
||||
}
|
||||
return prepareSnapshot(engine, history, stagingRoot, snapshot, fingerprint);
|
||||
return update;
|
||||
} catch (Throwable failure) {
|
||||
try {
|
||||
AtomicDirectoryPublisher.deleteTree(stagingRoot);
|
||||
@@ -52,11 +51,31 @@ record StudioGenerationUpdate(
|
||||
}
|
||||
}
|
||||
|
||||
private static StudioGenerationUpdate prepareSnapshot(IrisEngine engine, GenerationHistory history,
|
||||
Path stagingRoot, Path source, String fingerprint)
|
||||
private static StudioGenerationUpdate prepareStaged(IrisEngine engine, GenerationHistory history, Path source,
|
||||
PackTreeState sourceState, Path stagingRoot)
|
||||
throws IOException {
|
||||
Path snapshot = stagingRoot.resolve(source.getFileName());
|
||||
GenerationPackRepository.snapshotPackTree(source, snapshot, history.activePackLinkBasis().orElse(null));
|
||||
VerifiedPackTree pack = VerifiedPackTree.hash(snapshot);
|
||||
if (isActive(history.activeEpoch(), pack)) {
|
||||
return null;
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
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) throws IOException {
|
||||
GenerationEpoch active = history.activeEpoch();
|
||||
IrisData data = IrisData.openRuntime(source.toFile());
|
||||
IrisData data = IrisData.openRuntime(pack.root().toFile());
|
||||
try {
|
||||
IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey());
|
||||
if (replacement == null) {
|
||||
@@ -69,10 +88,10 @@ record StudioGenerationUpdate(
|
||||
if (!active.dimensionContract().hasSameLayout(contract)) {
|
||||
throw new IOException("Studio pack update changes the world's immutable dimension layout.");
|
||||
}
|
||||
GenerationRegistryContract registry = GenerationRegistryContractFactory.create(data, replacement, fingerprint);
|
||||
GenerationRegistryContract registry = GenerationRegistryContractFactory.create(data, replacement, pack.fingerprint());
|
||||
registry.requireDefinitionsAvailableIn(GenerationRegistryContractFactory.captureRequiredDefinitions(List.of(registry)));
|
||||
requireBuildableRuntime(engine, data, replacement, registry, stagingRoot.resolve(TRIAL_MANTLE_DIRECTORY));
|
||||
return new StudioGenerationUpdate(stagingRoot, source, fingerprint, contract, registry);
|
||||
return new StudioGenerationUpdate(stagingRoot, pack, sourceState, contract, registry);
|
||||
} finally {
|
||||
if (!data.isClosed()) {
|
||||
data.close();
|
||||
|
||||
@@ -52,7 +52,7 @@ import art.arcane.iris.world.runtime.WorldDeletionQueue;
|
||||
import art.arcane.iris.studio.jigsaw.JigsawStudioActivation;
|
||||
import art.arcane.iris.world.IrisToolbelt;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.world.history.EpochDurability;
|
||||
import art.arcane.iris.world.history.EpochPolicy;
|
||||
import art.arcane.iris.world.history.GenerationActivation;
|
||||
import art.arcane.iris.world.history.GenerationEpoch;
|
||||
import art.arcane.iris.world.history.GenerationEpochContractFactory;
|
||||
@@ -215,7 +215,7 @@ public class StudioSVC implements IrisService {
|
||||
File dimensionRoot,
|
||||
long worldSeed
|
||||
) {
|
||||
return installIntoWorld(sender, dimension, dimensionRoot, worldSeed, EpochDurability.configured());
|
||||
return installIntoWorld(sender, dimension, dimensionRoot, worldSeed, EpochPolicy.configured());
|
||||
}
|
||||
|
||||
public GenerationPublication installIntoWorld(
|
||||
@@ -223,9 +223,9 @@ public class StudioSVC implements IrisService {
|
||||
IrisDimension dimension,
|
||||
File dimensionRoot,
|
||||
long worldSeed,
|
||||
EpochDurability durability
|
||||
EpochPolicy epochPolicy
|
||||
) {
|
||||
return publishGenerationHistory(sender, dimension, dimensionRoot, worldSeed, false, durability);
|
||||
return publishGenerationHistory(sender, dimension, dimensionRoot, worldSeed, false, epochPolicy);
|
||||
}
|
||||
|
||||
public IrisDimension replaceIntoWorld(
|
||||
@@ -235,7 +235,7 @@ public class StudioSVC implements IrisService {
|
||||
long worldSeed
|
||||
) {
|
||||
GenerationPublication publication = publishGenerationHistory(
|
||||
sender, dimension, dimensionRoot, worldSeed, true, EpochDurability.configured());
|
||||
sender, dimension, dimensionRoot, worldSeed, true, EpochPolicy.configured());
|
||||
return publication == null ? null : publication.dimension();
|
||||
}
|
||||
|
||||
@@ -257,7 +257,7 @@ public class StudioSVC implements IrisService {
|
||||
File dimensionRoot,
|
||||
long worldSeed,
|
||||
boolean stageUpdate,
|
||||
EpochDurability durability
|
||||
EpochPolicy epochPolicy
|
||||
) {
|
||||
if (J.isPrimaryThread()) {
|
||||
sender.sendMessage(IrisLanguage.text(
|
||||
@@ -300,7 +300,7 @@ public class StudioSVC implements IrisService {
|
||||
worldSeed,
|
||||
candidate.dimensionContract(),
|
||||
candidate.registryContract(),
|
||||
durability
|
||||
epochPolicy
|
||||
);
|
||||
}
|
||||
Path installedPack = stageUpdate && history.pendingActivation().isPresent()
|
||||
|
||||
@@ -22,7 +22,7 @@ import art.arcane.volmlib.nativelib.NativeAdapters;
|
||||
import art.arcane.volmlib.nativelib.server.NativeServerDiagnostics;
|
||||
import art.arcane.iris.world.runtime.TransientWorldCleanupSupport;
|
||||
import art.arcane.iris.world.runtime.WorldRuntimeControlService;
|
||||
import art.arcane.iris.world.history.EpochDurability;
|
||||
import art.arcane.iris.world.history.EpochPolicy;
|
||||
import art.arcane.iris.world.history.GenerationHistory;
|
||||
import com.google.common.util.concurrent.AtomicDouble;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
@@ -271,9 +271,9 @@ public class IrisCreator {
|
||||
if (benchmark && !studio) {
|
||||
installedDimension = studioService.installIntoTransientWorld(sender, resolvedDimension, dimensionRoot);
|
||||
} else {
|
||||
EpochDurability durability = studio ? EpochDurability.UNSYNCED : EpochDurability.configured();
|
||||
EpochPolicy epochPolicy = studio ? EpochPolicy.STUDIO : EpochPolicy.configured();
|
||||
StudioSVC.GenerationPublication publication = studioService.installIntoWorld(
|
||||
sender, resolvedDimension, dimensionRoot, seed, durability);
|
||||
sender, resolvedDimension, dimensionRoot, seed, epochPolicy);
|
||||
installedDimension = publication == null ? null : publication.dimension();
|
||||
if (publication != null) {
|
||||
publishedHistory = publication.history();
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package art.arcane.iris.world.history;
|
||||
|
||||
import art.arcane.iris.world.storage.Durability;
|
||||
|
||||
/**
|
||||
* Whether publishing a generation epoch forces its pack files and directories to disk. Unsynced epochs can be
|
||||
* lost or torn by a crash, so they are only for histories that are discarded on restart, such as Studio worlds.
|
||||
*/
|
||||
public enum EpochDurability {
|
||||
SYNCED,
|
||||
UNSYNCED;
|
||||
|
||||
public static EpochDurability configured() {
|
||||
return Durability.enabled() ? SYNCED : UNSYNCED;
|
||||
}
|
||||
|
||||
public boolean syncs() {
|
||||
return this == SYNCED;
|
||||
}
|
||||
}
|
||||
@@ -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 epochs skip fsyncs, 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;
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ public final class GenerationHistory {
|
||||
GenerationKernelRegistry kernels
|
||||
) throws IOException {
|
||||
return create(new FreshCreation(dimensionRoot, packSource, packFingerprint, worldSeed, dimensionContract, registryContract),
|
||||
version, kernels, false, EpochDurability.configured());
|
||||
version, kernels, false, EpochPolicy.configured());
|
||||
}
|
||||
|
||||
public static GenerationHistory create(
|
||||
@@ -150,23 +150,23 @@ public final class GenerationHistory {
|
||||
long worldSeed,
|
||||
GenerationEpoch.DimensionContract dimensionContract,
|
||||
GenerationRegistryContract registryContract,
|
||||
EpochDurability durability
|
||||
EpochPolicy epochPolicy
|
||||
) throws IOException {
|
||||
GenerationKernelRegistry kernels = GenerationKernelRegistry.standard();
|
||||
return create(new FreshCreation(dimensionRoot, packSource, packFingerprint, worldSeed, dimensionContract, registryContract),
|
||||
kernels.current(), kernels, false, durability);
|
||||
kernels.current(), kernels, false, epochPolicy);
|
||||
}
|
||||
|
||||
public static GenerationHistory createUnpublished(FreshCreation creation) throws IOException {
|
||||
Objects.requireNonNull(creation, "creation");
|
||||
Files.createDirectory(creation.dimensionRoot());
|
||||
GenerationKernelRegistry kernels = GenerationKernelRegistry.standard();
|
||||
return create(creation, kernels.current(), kernels, true, EpochDurability.configured());
|
||||
return create(creation, kernels.current(), kernels, true, EpochPolicy.configured());
|
||||
}
|
||||
|
||||
private static GenerationHistory create(FreshCreation creation, GenerationKernelRegistry.Version version,
|
||||
GenerationKernelRegistry kernels, boolean unpublished,
|
||||
EpochDurability durability) throws IOException {
|
||||
EpochPolicy epochPolicy) throws IOException {
|
||||
Path dimensionRoot = creation.dimensionRoot();
|
||||
Path packSource = creation.packSource();
|
||||
String packFingerprint = creation.packFingerprint();
|
||||
@@ -195,14 +195,14 @@ public final class GenerationHistory {
|
||||
kernels
|
||||
);
|
||||
requireSourceFingerprint(packSource, epoch.packFingerprint(), epoch.packFingerprintVersion());
|
||||
GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot(), durability);
|
||||
GenerationPackRepository packs = new GenerationPackRepository(paths.dimensionRoot(), epochPolicy);
|
||||
Path publishedPack = packs.publish(
|
||||
epoch.epochId(),
|
||||
epoch.packFingerprint(),
|
||||
epoch.packFingerprintVersion(),
|
||||
packSource
|
||||
);
|
||||
forceEpochPublication(paths, epoch.epochId(), durability);
|
||||
forceEpochPublication(paths, epoch.epochId(), epochPolicy);
|
||||
GenerationSemanticIndex.initialize(paths.dimensionRoot());
|
||||
GenerationHistoryStore store = GenerationHistoryStore.initialize(paths.generationRoot(), epoch);
|
||||
return new GenerationHistory(paths, packs, store, ownership, kernels,
|
||||
@@ -330,7 +330,7 @@ public final class GenerationHistory {
|
||||
expectedEpoch.packFingerprint(),
|
||||
expectedEpoch.packFingerprintVersion()
|
||||
);
|
||||
forceEpochPublication(paths, expectedEpoch.epochId(), history.packs.durability());
|
||||
forceEpochPublication(paths, expectedEpoch.epochId(), history.packs.policy());
|
||||
}
|
||||
migrateLegacyMantle(paths, history.activeActivation().activationId());
|
||||
if (!legacyExists) {
|
||||
@@ -385,6 +385,75 @@ public final class GenerationHistory {
|
||||
GenerationRegistryContract registryContract,
|
||||
int transitionWidthBlocks,
|
||||
GenerationKernelRegistry.Version version
|
||||
) throws IOException {
|
||||
GenerationEpoch candidate = stageableCandidate(
|
||||
packFingerprint, packFingerprintVersion, dimensionContract, registryContract, version);
|
||||
Optional<GenerationActivation> pending = pendingActivationFor(candidate);
|
||||
if (pending.isPresent()) {
|
||||
return pending.get();
|
||||
}
|
||||
requireSourceFingerprint(
|
||||
packSource,
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
if (store.activeEpoch().equals(candidate)) {
|
||||
return requireActiveCandidate(candidate);
|
||||
}
|
||||
packs.publish(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion(),
|
||||
packSource,
|
||||
activePackLinkBasis().orElse(null)
|
||||
);
|
||||
return preparePublishedCandidate(candidate, transitionWidthBlocks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stages a pack tree this process already hashed. Unsynced histories move it into the epoch repository, so
|
||||
* neither the tree nor the published pack is hashed again; durable ones still copy, sync and re-hash it. The
|
||||
* tree must not be modified after it was hashed.
|
||||
*/
|
||||
public synchronized GenerationActivation stageVerifiedUpdate(
|
||||
VerifiedPackTree pack,
|
||||
GenerationEpoch.DimensionContract dimensionContract,
|
||||
GenerationRegistryContract registryContract,
|
||||
int transitionWidthBlocks
|
||||
) throws IOException {
|
||||
GenerationEpoch candidate = stageableCandidate(
|
||||
pack.fingerprint(), pack.fingerprintVersion(), dimensionContract, registryContract, kernels.current());
|
||||
Optional<GenerationActivation> pending = pendingActivationFor(candidate);
|
||||
if (pending.isPresent()) {
|
||||
return pending.get();
|
||||
}
|
||||
if (store.activeEpoch().equals(candidate)) {
|
||||
return requireActiveCandidate(candidate);
|
||||
}
|
||||
publishVerifiedPack(candidate, pack);
|
||||
return preparePublishedCandidate(candidate, transitionWidthBlocks);
|
||||
}
|
||||
|
||||
private void publishVerifiedPack(GenerationEpoch candidate, VerifiedPackTree pack) throws IOException {
|
||||
if (!packs.policy().syncs()) {
|
||||
packs.adopt(candidate.epochId(), pack);
|
||||
return;
|
||||
}
|
||||
packs.publish(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion(),
|
||||
pack.root(),
|
||||
activePackLinkBasis().orElse(null)
|
||||
);
|
||||
}
|
||||
|
||||
private GenerationEpoch stageableCandidate(
|
||||
String packFingerprint,
|
||||
int packFingerprintVersion,
|
||||
GenerationEpoch.DimensionContract dimensionContract,
|
||||
GenerationRegistryContract registryContract,
|
||||
GenerationKernelRegistry.Version version
|
||||
) throws IOException {
|
||||
GenerationEpoch candidate = epoch(
|
||||
packFingerprint,
|
||||
@@ -406,56 +475,51 @@ public final class GenerationHistory {
|
||||
if (!store.activeEpoch().dimensionContract().hasSameLayout(candidate.dimensionContract())) {
|
||||
throw new IllegalArgumentException("Generation update changes the immutable dimension contract.");
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
private Optional<GenerationActivation> pendingActivationFor(GenerationEpoch candidate) throws IOException {
|
||||
Optional<GenerationActivation> pending = store.pendingActivation();
|
||||
if (pending.isPresent()) {
|
||||
GenerationActivation activation = pending.get();
|
||||
if (!activation.epochId().equals(candidate.epochId())) {
|
||||
throw new IllegalStateException("A different generation activation is already pending.");
|
||||
}
|
||||
packs.requireExactPack(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
return activation;
|
||||
if (pending.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (store.activeEpoch().equals(candidate)) {
|
||||
requireSourceFingerprint(
|
||||
packSource,
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
packs.requireExactPack(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
return store.activeActivation();
|
||||
if (!pending.get().epochId().equals(candidate.epochId())) {
|
||||
throw new IllegalStateException("A different generation activation is already pending.");
|
||||
}
|
||||
|
||||
requireSourceFingerprint(
|
||||
packSource,
|
||||
packs.requireExactPack(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
packs.publish(
|
||||
return pending;
|
||||
}
|
||||
|
||||
private GenerationActivation requireActiveCandidate(GenerationEpoch candidate) throws IOException {
|
||||
packs.requireExactPack(
|
||||
candidate.epochId(),
|
||||
candidate.packFingerprint(),
|
||||
candidate.packFingerprintVersion(),
|
||||
packSource,
|
||||
activePackAsLinkBasis()
|
||||
candidate.packFingerprintVersion()
|
||||
);
|
||||
forceEpochPublication(paths, candidate.epochId(), packs.durability());
|
||||
return store.activeActivation();
|
||||
}
|
||||
|
||||
private GenerationActivation preparePublishedCandidate(
|
||||
GenerationEpoch candidate,
|
||||
int transitionWidthBlocks
|
||||
) throws IOException {
|
||||
forceEpochPublication(paths, candidate.epochId(), packs.policy());
|
||||
return store.preparePendingActivation(candidate, transitionWidthBlocks);
|
||||
}
|
||||
|
||||
private Path activePackAsLinkBasis() {
|
||||
/**
|
||||
* 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 packs.requireSafePackRoot(store.activeEpoch().epochId());
|
||||
return Optional.of(packs.requireSafePackRoot(store.activeEpoch().epochId()));
|
||||
} catch (IOException missingOrUnsafe) {
|
||||
return null;
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1355,14 +1419,14 @@ public final class GenerationHistory {
|
||||
private static void forceEpochPublication(
|
||||
GenerationHistoryPaths paths,
|
||||
String epochId,
|
||||
EpochDurability durability
|
||||
EpochPolicy epochPolicy
|
||||
) throws IOException {
|
||||
Path epochRoot = paths.epochRoot(epochId);
|
||||
if (!Files.isDirectory(epochRoot, LinkOption.NOFOLLOW_LINKS)
|
||||
|| Files.isSymbolicLink(epochRoot)) {
|
||||
throw new IOException("Generation epoch is not a safe directory: " + epochRoot);
|
||||
}
|
||||
if (!durability.syncs() || File.separatorChar == '\\') {
|
||||
if (!epochPolicy.syncs() || File.separatorChar == '\\') {
|
||||
return;
|
||||
}
|
||||
GenerationPackRepository.forceDirectoryTree(epochRoot, GenerationHistory::forceDirectory);
|
||||
|
||||
@@ -19,7 +19,9 @@ import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CancellationException;
|
||||
@@ -41,24 +43,25 @@ public final class GenerationPackRepository {
|
||||
private final Path dimensionRoot;
|
||||
private final Path generationRoot;
|
||||
private final Path epochsRoot;
|
||||
private final EpochDurability durability;
|
||||
private final EpochPolicy policy;
|
||||
private final Set<String> verifiedPacks = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public GenerationPackRepository(Path dimensionRoot) {
|
||||
this(dimensionRoot, EpochDurability.configured());
|
||||
this(dimensionRoot, EpochPolicy.configured());
|
||||
}
|
||||
|
||||
public GenerationPackRepository(Path dimensionRoot, EpochDurability durability) {
|
||||
public GenerationPackRepository(Path dimensionRoot, EpochPolicy policy) {
|
||||
Path root = Objects.requireNonNull(dimensionRoot, "dimensionRoot")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
this.dimensionRoot = root;
|
||||
generationRoot = root.resolve("iris").resolve("generation");
|
||||
epochsRoot = generationRoot.resolve("epochs");
|
||||
this.durability = Objects.requireNonNull(durability, "durability");
|
||||
this.policy = Objects.requireNonNull(policy, "policy");
|
||||
}
|
||||
|
||||
public EpochDurability durability() {
|
||||
return durability;
|
||||
public EpochPolicy policy() {
|
||||
return policy;
|
||||
}
|
||||
|
||||
public Path generationRoot() {
|
||||
@@ -124,37 +127,100 @@ public final class GenerationPackRepository {
|
||||
Files.delete(stage);
|
||||
copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), publicationCopyMode(), basisPack);
|
||||
requireFingerprint(stage, packFingerprint, packFingerprintVersion);
|
||||
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");
|
||||
return target;
|
||||
return commitStage(epochId, stage, packFingerprint, packFingerprintVersion);
|
||||
} finally {
|
||||
if (Files.exists(stage, LinkOption.NOFOLLOW_LINKS)) {
|
||||
AtomicDirectoryPublisher.deleteTree(stage);
|
||||
}
|
||||
deleteLeftoverStage(stage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes a tree this process already hashed by moving it into place instead of copying and hashing it again.
|
||||
* The tree must be on the repository's filesystem and is consumed. Its files were never synced, so only
|
||||
* repositories that skip fsyncs may adopt one.
|
||||
*/
|
||||
public synchronized Path adopt(String epochId, VerifiedPackTree pack) throws IOException {
|
||||
if (policy.syncs()) {
|
||||
throw new IllegalStateException("Durable generation epochs cannot adopt an unsynced pack tree.");
|
||||
}
|
||||
String requiredEpochId = requireDigest(epochId, "epochId");
|
||||
requireDigest(pack.fingerprint(), "packFingerprint");
|
||||
ensureEpochsRoot();
|
||||
try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire(
|
||||
epochsRoot,
|
||||
".epoch-" + requiredEpochId + ".lock"
|
||||
)) {
|
||||
ensureEpochsRoot();
|
||||
return adoptLocked(requiredEpochId, pack);
|
||||
}
|
||||
}
|
||||
|
||||
private Path adoptLocked(String epochId, VerifiedPackTree pack) throws IOException {
|
||||
Path epochDirectory = ensureChildDirectory(epochsRoot, epochId);
|
||||
if (Files.exists(epochDirectory.resolve("pack"), LinkOption.NOFOLLOW_LINKS)) {
|
||||
return requireExactPack(epochId, pack.fingerprint(), pack.fingerprintVersion());
|
||||
}
|
||||
Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
|
||||
try {
|
||||
Files.delete(stage);
|
||||
Files.move(pack.root(), stage, StandardCopyOption.ATOMIC_MOVE);
|
||||
return commitStage(epochId, stage, pack.fingerprint(), pack.fingerprintVersion());
|
||||
} finally {
|
||||
deleteLeftoverStage(stage);
|
||||
}
|
||||
}
|
||||
|
||||
private Path commitStage(String epochId, Path stage, String packFingerprint, int packFingerprintVersion)
|
||||
throws IOException {
|
||||
Path epochDirectory = stage.getParent();
|
||||
Path target = epochDirectory.resolve("pack");
|
||||
try (AtomicDirectoryPublisher.Publication publication =
|
||||
AtomicDirectoryPublisher.publishAbsent(stage, target)) {
|
||||
publication.commit();
|
||||
} catch (FileAlreadyExistsException race) {
|
||||
return requireExactPack(epochId, packFingerprint, packFingerprintVersion);
|
||||
}
|
||||
syncDirectory(epochDirectory);
|
||||
validateExistingAncestors(epochId);
|
||||
requireSafeDirectory(target, "Generation epoch pack is missing or unsafe");
|
||||
rememberVerifiedPack(epochId, packFingerprint, packFingerprintVersion);
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void deleteLeftoverStage(Path stage) throws IOException {
|
||||
if (Files.exists(stage, LinkOption.NOFOLLOW_LINKS)) {
|
||||
AtomicDirectoryPublisher.deleteTree(stage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes the published pack unless this repository trusts packs it verified itself and already did so.
|
||||
*/
|
||||
public Path requireExactPack(
|
||||
String epochId,
|
||||
String packFingerprint,
|
||||
int packFingerprintVersion
|
||||
) throws IOException {
|
||||
Path pack = requireSafePackRoot(epochId);
|
||||
requireFingerprint(
|
||||
pack,
|
||||
requireDigest(packFingerprint, "packFingerprint"),
|
||||
packFingerprintVersion
|
||||
);
|
||||
String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
|
||||
if (policy.trustsVerifiedPacks()
|
||||
&& verifiedPacks.contains(verifiedPackKey(epochId, requiredFingerprint, packFingerprintVersion))) {
|
||||
return pack;
|
||||
}
|
||||
requireFingerprint(pack, requiredFingerprint, packFingerprintVersion);
|
||||
rememberVerifiedPack(epochId, requiredFingerprint, packFingerprintVersion);
|
||||
return pack;
|
||||
}
|
||||
|
||||
private void rememberVerifiedPack(String epochId, String packFingerprint, int packFingerprintVersion) {
|
||||
if (policy.trustsVerifiedPacks()) {
|
||||
verifiedPacks.add(verifiedPackKey(epochId, packFingerprint, packFingerprintVersion));
|
||||
}
|
||||
}
|
||||
|
||||
private static String verifiedPackKey(String epochId, String packFingerprint, int packFingerprintVersion) {
|
||||
return epochId + '/' + packFingerprintVersion + '/' + packFingerprint;
|
||||
}
|
||||
|
||||
Path requireSafePackRoot(String epochId) throws IOException {
|
||||
String requiredEpochId = requireDigest(epochId, "epochId");
|
||||
validateExistingAncestors(requiredEpochId);
|
||||
@@ -186,7 +252,7 @@ public final class GenerationPackRepository {
|
||||
}
|
||||
|
||||
private PackCopyMode publicationCopyMode() {
|
||||
return durability.syncs() ? PackCopyMode.DURABLE : PackCopyMode.SCRATCH;
|
||||
return policy.syncs() ? PackCopyMode.DURABLE : PackCopyMode.SCRATCH;
|
||||
}
|
||||
|
||||
private Path ensureChildDirectory(Path parent, String name) throws IOException {
|
||||
@@ -223,7 +289,7 @@ public final class GenerationPackRepository {
|
||||
}
|
||||
|
||||
private void syncDirectory(Path directory) throws IOException {
|
||||
if (!durability.syncs() || File.separatorChar == '\\') {
|
||||
if (!policy.syncs() || File.separatorChar == '\\') {
|
||||
return;
|
||||
}
|
||||
try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) {
|
||||
@@ -238,10 +304,11 @@ public final class GenerationPackRepository {
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a pack without syncing it, for scratch copies that are discarded and never published.
|
||||
* 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.
|
||||
*/
|
||||
public static void snapshotPackTree(Path source, Path target) throws IOException {
|
||||
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, null);
|
||||
public static void snapshotPackTree(Path source, Path target, Path basisPack) throws IOException {
|
||||
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, basisPack);
|
||||
}
|
||||
|
||||
static void copyPackTree(Path source, Path target, Executor executor, int workers) throws IOException {
|
||||
@@ -255,14 +322,7 @@ public final class GenerationPackRepository {
|
||||
if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) {
|
||||
throw new IllegalArgumentException("Pack copy workers must be between 1 and " + MAXIMUM_COPY_WORKERS + ".");
|
||||
}
|
||||
Path sourcePath = Objects.requireNonNull(source, "source").toAbsolutePath().normalize();
|
||||
if (Files.isSymbolicLink(sourcePath)) {
|
||||
throw new IOException("Pack source is a symbolic link: " + sourcePath);
|
||||
}
|
||||
Path normalizedSource = sourcePath.toRealPath();
|
||||
if (!Files.isDirectory(normalizedSource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Pack source is not a directory: " + normalizedSource);
|
||||
}
|
||||
Path normalizedSource = requirePackSource(source);
|
||||
Path normalizedTarget = Objects.requireNonNull(target, "target").toAbsolutePath().normalize();
|
||||
if (Files.exists(normalizedTarget, LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(normalizedTarget)) {
|
||||
throw new IOException("Pack publication stage already exists: " + normalizedTarget);
|
||||
@@ -272,7 +332,41 @@ public final class GenerationPackRepository {
|
||||
+ normalizedSource + " and " + normalizedTarget);
|
||||
}
|
||||
|
||||
List<Path> sourceFiles = new ArrayList<>();
|
||||
PackTreeState sourceState = walkPackTree(normalizedSource, directory ->
|
||||
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory)));
|
||||
List<Path> sourceFiles = sourceState.files().keySet().stream().map(normalizedSource::resolve).toList();
|
||||
Path basis = basisPack == null ? null : basisPack.toAbsolutePath().normalize();
|
||||
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)) {
|
||||
return;
|
||||
}
|
||||
Files.copy(sourceFile, destination, StandardCopyOption.COPY_ATTRIBUTES);
|
||||
unsyncedCopies.add(destination);
|
||||
});
|
||||
if (mode == PackCopyMode.DURABLE) {
|
||||
executeFilePhase(List.copyOf(unsyncedCopies), executor, workers, GenerationPackRepository::forceFile);
|
||||
}
|
||||
}
|
||||
|
||||
static Path requirePackSource(Path source) throws IOException {
|
||||
Path sourcePath = Objects.requireNonNull(source, "source").toAbsolutePath().normalize();
|
||||
if (Files.isSymbolicLink(sourcePath)) {
|
||||
throw new IOException("Pack source is a symbolic link: " + sourcePath);
|
||||
}
|
||||
Path normalizedSource = sourcePath.toRealPath();
|
||||
if (!Files.isDirectory(normalizedSource, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Pack source is not a directory: " + normalizedSource);
|
||||
}
|
||||
return normalizedSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits every directory and lists every file a pack copy includes, rejecting links and special files.
|
||||
*/
|
||||
static PackTreeState walkPackTree(Path normalizedSource, FileAction includedDirectory) throws IOException {
|
||||
Map<Path, PackTreeState.FileStamp> files = new LinkedHashMap<>();
|
||||
Files.walkFileTree(normalizedSource, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
|
||||
@@ -284,7 +378,7 @@ public final class GenerationPackRepository {
|
||||
&& PackDirectoryResolver.isHiddenName(directory.getFileName().toString())) {
|
||||
return FileVisitResult.SKIP_SUBTREE;
|
||||
}
|
||||
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory));
|
||||
includedDirectory.run(directory);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@@ -302,7 +396,7 @@ public final class GenerationPackRepository {
|
||||
|| fileName.endsWith(".code-workspace")) {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
sourceFiles.add(file);
|
||||
files.put(relative, new PackTreeState.FileStamp(attributes.size(), attributes.lastModifiedTime()));
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@@ -311,20 +405,7 @@ public final class GenerationPackRepository {
|
||||
throw new IOException("Unable to copy pack entry: " + file, failure);
|
||||
}
|
||||
});
|
||||
Path basis = basisPack == null ? null : basisPack.toAbsolutePath().normalize();
|
||||
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)) {
|
||||
return;
|
||||
}
|
||||
Files.copy(sourceFile, destination, StandardCopyOption.COPY_ATTRIBUTES);
|
||||
unsyncedCopies.add(destination);
|
||||
});
|
||||
if (mode == PackCopyMode.SCRATCH) {
|
||||
return;
|
||||
}
|
||||
executeFilePhase(List.copyOf(unsyncedCopies), executor, workers, GenerationPackRepository::forceFile);
|
||||
return new PackTreeState(files);
|
||||
}
|
||||
|
||||
private static boolean linkUnchangedFile(Path relative, Path sourceFile, Path basis, Path destination) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+23
-17
@@ -40,45 +40,49 @@ public final class StudioGenerationUpdateTest {
|
||||
public final TemporaryFolder temporary = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void unchangedSourceNeedsNoSnapshotOrManifestUpdate() throws Exception {
|
||||
public void unchangedSourceNeedsNoManifestUpdateAndLeavesNoSnapshot() throws Exception {
|
||||
Path source = temporary.newFolder("unchanged-pack").toPath();
|
||||
Files.createDirectories(source.resolve("dimensions"));
|
||||
Files.writeString(source.resolve("dimensions/test.json"), "{}");
|
||||
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
|
||||
IrisEngine engine = mock(IrisEngine.class);
|
||||
GenerationHistory history = mock(GenerationHistory.class);
|
||||
GenerationEpoch active = mock(GenerationEpoch.class);
|
||||
when(engine.getStudioGenerationSource()).thenReturn(source);
|
||||
when(history.activeEpoch()).thenReturn(active);
|
||||
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
|
||||
when(active.packFingerprint()).thenReturn(fingerprint);
|
||||
|
||||
assertNull(StudioGenerationUpdate.prepare(engine, history));
|
||||
|
||||
verify(history).activeEpoch();
|
||||
verifyNoMoreInteractions(history);
|
||||
assertUnchangedSourceStagesNothing(source, source);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unchangedAuthoringRootAliasNeedsNoSnapshot() throws Exception {
|
||||
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));
|
||||
}
|
||||
|
||||
private void assertUnchangedSourceStagesNothing(Path authoringRoot, Path source) throws Exception {
|
||||
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
|
||||
GenerationHistoryPaths paths = GenerationHistoryPaths.forDimension(temporary.newFolder().toPath());
|
||||
Files.createDirectories(paths.generationRoot());
|
||||
Files.writeString(paths.manifest(), "unchanged manifest");
|
||||
IrisEngine engine = mock(IrisEngine.class);
|
||||
GenerationHistory history = mock(GenerationHistory.class);
|
||||
GenerationEpoch active = mock(GenerationEpoch.class);
|
||||
when(engine.getStudioGenerationSource()).thenReturn(alias);
|
||||
when(engine.getStudioGenerationSource()).thenReturn(authoringRoot);
|
||||
when(history.activeEpoch()).thenReturn(active);
|
||||
when(history.paths()).thenReturn(paths);
|
||||
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
|
||||
when(active.packFingerprint()).thenReturn(fingerprint);
|
||||
|
||||
assertNull(StudioGenerationUpdate.prepare(engine, history));
|
||||
|
||||
assertThrows(IOException.class, () -> GenerationPackFingerprint.compute(alias, GenerationPackFingerprint.CURRENT_VERSION));
|
||||
assertEquals("unchanged manifest", Files.readString(paths.manifest()));
|
||||
try (Stream<Path> entries = Files.list(paths.generationRoot())) {
|
||||
assertEquals(1L, entries.count());
|
||||
}
|
||||
verify(history).activeEpoch();
|
||||
verify(history).paths();
|
||||
verify(history).activePackLinkBasis();
|
||||
verifyNoMoreInteractions(history);
|
||||
}
|
||||
|
||||
@@ -112,6 +116,7 @@ public final class StudioGenerationUpdateTest {
|
||||
}
|
||||
verify(history, times(2)).activeEpoch();
|
||||
verify(history).paths();
|
||||
verify(history).activePackLinkBasis();
|
||||
verifyNoMoreInteractions(history);
|
||||
}
|
||||
|
||||
@@ -130,7 +135,7 @@ public final class StudioGenerationUpdateTest {
|
||||
|
||||
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
|
||||
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("rejected symbolic link"));
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("Pack contains a symbolic link"));
|
||||
verifyNoInteractions(history);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +167,7 @@ public final class StudioGenerationUpdateTest {
|
||||
}
|
||||
verify(history, times(2)).activeEpoch();
|
||||
verify(history).paths();
|
||||
verify(history).activePackLinkBasis();
|
||||
verifyNoMoreInteractions(history);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,12 +68,12 @@ public class GenerationHistoryTest extends GenerationHistorySupport {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onlyUnsyncedHistoriesSkipTheEpochTreeSyncWhenStaging() throws Exception {
|
||||
public void onlyDurableHistoriesSyncTheEpochTreeWhenStaging() throws Exception {
|
||||
String previous = System.getProperty(Durability.MODE_PROPERTY);
|
||||
System.clearProperty(Durability.MODE_PROPERTY);
|
||||
try {
|
||||
assertEquals(1, stagingEpochTreeSyncs("synced", EpochDurability.SYNCED));
|
||||
assertEquals(0, stagingEpochTreeSyncs("unsynced", EpochDurability.UNSYNCED));
|
||||
assertEquals(1, stagingEpochTreeSyncs("durable", EpochPolicy.DURABLE));
|
||||
assertEquals(0, stagingEpochTreeSyncs("studio", EpochPolicy.STUDIO));
|
||||
} finally {
|
||||
if (previous != null) {
|
||||
System.setProperty(Durability.MODE_PROPERTY, previous);
|
||||
@@ -81,12 +81,41 @@ public class GenerationHistoryTest extends GenerationHistorySupport {
|
||||
}
|
||||
}
|
||||
|
||||
private int stagingEpochTreeSyncs(String name, EpochDurability durability) throws Exception {
|
||||
@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());
|
||||
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(), durability);
|
||||
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) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
@@ -80,8 +81,8 @@ public class GenerationPackRepositoryTest {
|
||||
Path source = createPack("unsynced-source", "{}");
|
||||
Path syncedWorld = temporaryFolder.newFolder("synced-world").toPath();
|
||||
Path unsyncedWorld = temporaryFolder.newFolder("unsynced-world").toPath();
|
||||
GenerationPackRepository synced = new GenerationPackRepository(syncedWorld, EpochDurability.SYNCED);
|
||||
GenerationPackRepository unsynced = new GenerationPackRepository(unsyncedWorld, EpochDurability.UNSYNCED);
|
||||
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));
|
||||
@@ -99,9 +100,9 @@ public class GenerationPackRepositoryTest {
|
||||
String previous = System.getProperty(Durability.MODE_PROPERTY);
|
||||
try {
|
||||
System.clearProperty(Durability.MODE_PROPERTY);
|
||||
assertEquals(EpochDurability.SYNCED, new GenerationPackRepository(dimensionRoot).durability());
|
||||
assertEquals(EpochPolicy.DURABLE, new GenerationPackRepository(dimensionRoot).policy());
|
||||
System.setProperty(Durability.MODE_PROPERTY, "relaxed");
|
||||
assertEquals(EpochDurability.UNSYNCED, new GenerationPackRepository(dimensionRoot).durability());
|
||||
assertEquals(EpochPolicy.RELAXED, new GenerationPackRepository(dimensionRoot).policy());
|
||||
} finally {
|
||||
if (previous == null) {
|
||||
System.clearProperty(Durability.MODE_PROPERTY);
|
||||
@@ -116,12 +117,94 @@ public class GenerationPackRepositoryTest {
|
||||
Path source = createPack("snapshot-source", "{}");
|
||||
Path snapshot = temporaryFolder.getRoot().toPath().resolve("snapshot");
|
||||
|
||||
GenerationPackRepository.snapshotPackTree(source, snapshot);
|
||||
GenerationPackRepository.snapshotPackTree(source, snapshot, 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);
|
||||
|
||||
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 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);
|
||||
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);
|
||||
AtomicInteger hashes = new AtomicInteger();
|
||||
try (MockedStatic<GenerationPackFingerprint> ignored = countingHashes(hashes)) {
|
||||
durable.requireExactPack(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION);
|
||||
durable.requireExactPack(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION);
|
||||
}
|
||||
|
||||
assertEquals(2, hashes.get());
|
||||
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
|
||||
assertThrows(IllegalStateException.class, () -> durable.adopt(digest('b'), verified));
|
||||
}
|
||||
|
||||
private static MockedStatic<GenerationPackFingerprint> countingHashes(AtomicInteger hashes) {
|
||||
return mockStatic(GenerationPackFingerprint.class, invocation -> {
|
||||
if (invocation.getMethod().getName().equals("compute")) {
|
||||
hashes.incrementAndGet();
|
||||
}
|
||||
return invocation.callRealMethod();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsMutationOfAnExistingEpoch() throws Exception {
|
||||
Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath();
|
||||
|
||||
Reference in new issue
Block a user