mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Merge master into hydrology
This commit is contained in:
commit
52dae154bb
35 files changed
+3025
-1835
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1,233 +1,12 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import art.arcane.iris.world.lifecycle.BukkitStartupPaths;
|
||||
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration;
|
||||
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry;
|
||||
import art.arcane.iris.world.lifecycle.HuskWorldQuarantine;
|
||||
import art.arcane.iris.world.lifecycle.MissingWorldStorageLog;
|
||||
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap;
|
||||
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest;
|
||||
import art.arcane.iris.pack.datapack.DataVersion;
|
||||
import io.papermc.paper.ServerBuildInfo;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult;
|
||||
import art.arcane.iris.platform.bootstrap.SlimJar;
|
||||
import art.arcane.iris.world.safeguard.GenerationRefusalNotice;
|
||||
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
|
||||
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
|
||||
import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public final class IrisBootstrap implements PluginBootstrap {
|
||||
@Override
|
||||
public void bootstrap(BootstrapContext context) {
|
||||
WorldReplacementBootstrapMarker.markBootstrapped();
|
||||
try {
|
||||
loadRuntimeLibraries(context);
|
||||
BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent();
|
||||
reconcilePendingWorldReplacements(context, startupPaths);
|
||||
quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message));
|
||||
requireUsableWorldStorage(startupPaths);
|
||||
ProvisionResult provisioned = provision(context, startupPaths);
|
||||
Path datapackRoot = provisioned.datapackRoot();
|
||||
context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot);
|
||||
} catch (Throwable failure) {
|
||||
armStartupFailure(context, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadRuntimeLibraries(BootstrapContext context) {
|
||||
SlimJar.loadBootstrap(
|
||||
context.getDataDirectory().resolve("cache").resolve("libraries"),
|
||||
ServerBuildInfo.buildInfo().minecraftVersionId(),
|
||||
new SlimJar.BootstrapLogger() {
|
||||
@Override
|
||||
public void info(String message) {
|
||||
context.getLogger().info(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
context.getLogger().error(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String message) {
|
||||
context.getLogger().debug(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void reconcilePendingWorldReplacements(
|
||||
BootstrapContext context,
|
||||
BukkitStartupPaths startupPaths
|
||||
) {
|
||||
try {
|
||||
WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile(
|
||||
context.getDataDirectory(),
|
||||
startupPaths.levelRoot(),
|
||||
startupPaths.bukkitConfiguration(),
|
||||
message -> context.getLogger().info(message)
|
||||
);
|
||||
if (result.transactions() > 0) {
|
||||
context.getLogger().info(
|
||||
"Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained",
|
||||
result.transactions(),
|
||||
result.published(),
|
||||
result.rolledBack(),
|
||||
result.retained()
|
||||
);
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to reconcile pending Iris world replacements before registry bootstrap",
|
||||
failure
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a hot-deleted world's husk out of {@code <levelRoot>/dimensions/iris} before anything enumerates
|
||||
* it.
|
||||
* <p>
|
||||
* Deleting a loaded world's folder and letting the server save the level back leaves a directory holding
|
||||
* only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is
|
||||
* classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from
|
||||
* the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes
|
||||
* no console input and hangs startup forever. The folder is moved rather than deleted, so it stays
|
||||
* recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless.
|
||||
*/
|
||||
static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer<String> warn) {
|
||||
HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from.
|
||||
* <p>
|
||||
* The server enumerates levels from {@code <levelRoot>/dimensions/<namespace>/<key>} on disk, so a world
|
||||
* whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world
|
||||
* it cannot generate with a fail-closed generator, which stops startup at that world's own level creation,
|
||||
* after the levels before it have loaded. A pack snapshot that has gone missing is found here instead,
|
||||
* before any level is created, exactly as a corrupt {@code dimensions/<id>.json} is. An Iris world in a
|
||||
* vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it
|
||||
* with the vanilla generator without ever asking Iris.
|
||||
* <p>
|
||||
* A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and
|
||||
* its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither
|
||||
* is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has
|
||||
* already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder,
|
||||
* or a move that failed) owns nothing to lose. Both are only reported here.
|
||||
*/
|
||||
static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException {
|
||||
Path levelRoot = startupPaths.levelRoot();
|
||||
Path levelName = levelRoot.getFileName();
|
||||
if (levelName == null || levelName.toString().isBlank()) {
|
||||
throw new IOException("Configured level root has no startup level id: " + levelRoot);
|
||||
}
|
||||
List<IrisWorldStorageEntry> entries = BukkitWorldConfiguration.auditIrisWorldStorage(
|
||||
startupPaths.bukkitConfiguration().toFile(),
|
||||
levelName.toString(),
|
||||
levelRoot
|
||||
);
|
||||
StringBuilder unusable = new StringBuilder();
|
||||
StringBuilder unbound = new StringBuilder();
|
||||
for (IrisWorldStorageEntry entry : entries) {
|
||||
switch (entry.state()) {
|
||||
case PRESENT -> {
|
||||
}
|
||||
case MISSING -> MissingWorldStorageLog.warnOnce(
|
||||
entry.configuredWorldName(),
|
||||
entry.storagePath());
|
||||
case EMPTY -> MissingWorldStorageLog.warnEmptyOnce(
|
||||
entry.configuredWorldName(),
|
||||
entry.storagePath());
|
||||
case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(" (")
|
||||
.append(entry.storagePath())
|
||||
.append(": ")
|
||||
.append(entry.detail() == null ? "storage is unusable" : entry.detail())
|
||||
.append(')');
|
||||
case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(" (")
|
||||
.append(entry.storagePath())
|
||||
.append("): set worlds.")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(".generator to Iris:<pack> in bukkit.yml, or move the folder aside to start a new"
|
||||
+ " vanilla world there");
|
||||
}
|
||||
}
|
||||
List<String> refusals = new ArrayList<>(2);
|
||||
if (!unusable.isEmpty()) {
|
||||
refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: "
|
||||
+ unusable + ". Restore each world folder from a backup, or move it aside; a world with no"
|
||||
+ " folder is reported and skipped, and the server starts.");
|
||||
}
|
||||
if (!unbound.isEmpty()) {
|
||||
refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla"
|
||||
+ " terrain into them: " + unbound + ".");
|
||||
}
|
||||
if (!refusals.isEmpty()) {
|
||||
throw new IllegalStateException(String.join(" ", refusals));
|
||||
}
|
||||
}
|
||||
|
||||
static void armStartupFailure(BootstrapContext context, Throwable failure) {
|
||||
armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY);
|
||||
}
|
||||
|
||||
static <E extends LifecycleEvent> void armStartupFailure(
|
||||
BootstrapContext context,
|
||||
Throwable failure,
|
||||
LifecycleEventType<? super BootstrapContext, ? extends E, ?> eventType
|
||||
) {
|
||||
context.getLifecycleManager().registerEventHandler(eventType, event -> {
|
||||
throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure);
|
||||
});
|
||||
List<String> notice = startupRefusalNotice(failure);
|
||||
try {
|
||||
for (String line : notice) {
|
||||
context.getLogger().error(line);
|
||||
}
|
||||
context.getLogger().warn("Iris bootstrap failure", failure);
|
||||
} catch (Throwable loggingFailure) {
|
||||
notice.forEach(System.err::println);
|
||||
failure.addSuppressed(loggingFailure);
|
||||
failure.printStackTrace(System.err);
|
||||
}
|
||||
}
|
||||
|
||||
static List<String> startupRefusalNotice(Throwable failure) {
|
||||
return GenerationRefusalNotice.compose(
|
||||
"Iris stopped server startup before any world loads",
|
||||
GenerationRefusalNotice.causes(failure),
|
||||
List.of(
|
||||
"Startup stops at datapack discovery: no world loads and no chunks are written.",
|
||||
"Fix the cause, then start the server again. Paper's --safeMode hint does not apply:"
|
||||
+ " Iris worlds must not load without Iris."
|
||||
));
|
||||
}
|
||||
|
||||
private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) {
|
||||
try {
|
||||
return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest(
|
||||
context.getDataDirectory(),
|
||||
message -> context.getLogger().info(message),
|
||||
startupPaths,
|
||||
DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId())
|
||||
));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Unable to provision the Iris startup datapack", e);
|
||||
}
|
||||
IrisPluginRuntime.bootstrap(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import art.arcane.iris.world.lifecycle.BukkitStartupPaths;
|
||||
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration;
|
||||
import art.arcane.iris.world.lifecycle.BukkitWorldConfiguration.IrisWorldStorageEntry;
|
||||
import art.arcane.iris.world.lifecycle.HuskWorldQuarantine;
|
||||
import art.arcane.iris.world.lifecycle.MissingWorldStorageLog;
|
||||
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrap;
|
||||
import art.arcane.iris.world.lifecycle.WorldReplacementBootstrapMarker;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.BootstrapRequest;
|
||||
import art.arcane.iris.pack.datapack.DataVersion;
|
||||
import io.papermc.paper.ServerBuildInfo;
|
||||
import art.arcane.iris.pack.DefaultPackBootstrapProvisioner.ProvisionResult;
|
||||
import art.arcane.iris.platform.bootstrap.SlimJar;
|
||||
import art.arcane.iris.world.safeguard.GenerationRefusalNotice;
|
||||
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
|
||||
import io.papermc.paper.plugin.lifecycle.event.LifecycleEvent;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEventType;
|
||||
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
final class IrisBootstrapSequence {
|
||||
private IrisBootstrapSequence() {
|
||||
}
|
||||
|
||||
static void bootstrap(BootstrapContext context) {
|
||||
WorldReplacementBootstrapMarker.markBootstrapped();
|
||||
try {
|
||||
loadRuntimeLibraries(context);
|
||||
BukkitStartupPaths startupPaths = BukkitStartupPaths.resolveCurrent();
|
||||
reconcilePendingWorldReplacements(context, startupPaths);
|
||||
quarantineWorthlessHusks(startupPaths, message -> context.getLogger().warn(message));
|
||||
requireUsableWorldStorage(startupPaths);
|
||||
ProvisionResult provisioned = provision(context, startupPaths);
|
||||
Path datapackRoot = provisioned.datapackRoot();
|
||||
context.getLogger().info("Iris startup datapack is {} at {}", provisioned.status(), datapackRoot);
|
||||
} catch (Throwable failure) {
|
||||
armStartupFailure(context, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadRuntimeLibraries(BootstrapContext context) {
|
||||
SlimJar.loadBootstrap(
|
||||
context.getDataDirectory().resolve("cache").resolve("libraries"),
|
||||
ServerBuildInfo.buildInfo().minecraftVersionId(),
|
||||
new SlimJar.BootstrapLogger() {
|
||||
@Override
|
||||
public void info(String message) {
|
||||
context.getLogger().info(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
context.getLogger().error(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String message) {
|
||||
context.getLogger().debug(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void reconcilePendingWorldReplacements(
|
||||
BootstrapContext context,
|
||||
BukkitStartupPaths startupPaths
|
||||
) {
|
||||
try {
|
||||
WorldReplacementBootstrap.ReconcileResult result = WorldReplacementBootstrap.reconcile(
|
||||
context.getDataDirectory(),
|
||||
startupPaths.levelRoot(),
|
||||
startupPaths.bukkitConfiguration(),
|
||||
message -> context.getLogger().info(message)
|
||||
);
|
||||
if (result.transactions() > 0) {
|
||||
context.getLogger().info(
|
||||
"Reconciled {} pending Iris world replacement(s): {} published, {} rolled back, {} retained",
|
||||
result.transactions(),
|
||||
result.published(),
|
||||
result.rolledBack(),
|
||||
result.retained()
|
||||
);
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
throw new IllegalStateException(
|
||||
"Unable to reconcile pending Iris world replacements before registry bootstrap",
|
||||
failure
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a hot-deleted world's husk out of {@code <levelRoot>/dimensions/iris} before anything enumerates
|
||||
* it.
|
||||
* <p>
|
||||
* Deleting a loaded world's folder and letting the server save the level back leaves a directory holding
|
||||
* only the server's own {@code data/} skeleton. Left there it stops the boot whichever way it is
|
||||
* classified: as unusable storage it trips the guard below, and as an empty folder it is excluded from
|
||||
* the dimension registry, which trips Paper's interactive world-migration gate - a prompt that consumes
|
||||
* no console input and hangs startup forever. The folder is moved rather than deleted, so it stays
|
||||
* recoverable; {@link HuskWorldQuarantine} refuses anything that is not provably worthless.
|
||||
*/
|
||||
static void quarantineWorthlessHusks(BukkitStartupPaths startupPaths, Consumer<String> warn) {
|
||||
HuskWorldQuarantine.quarantineWorthlessHusks(startupPaths.levelRoot(), warn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops startup when a world the server is about to load carries Iris storage Iris cannot generate from.
|
||||
* <p>
|
||||
* The server enumerates levels from {@code <levelRoot>/dimensions/<namespace>/<key>} on disk, so a world
|
||||
* whose folder is present is going to be loaded whatever Iris does. The generator resolver answers a world
|
||||
* it cannot generate with a fail-closed generator, which stops startup at that world's own level creation,
|
||||
* after the levels before it have loaded. A pack snapshot that has gone missing is found here instead,
|
||||
* before any level is created, exactly as a corrupt {@code dimensions/<id>.json} is. An Iris world in a
|
||||
* vanilla slot whose bukkit.yml entry no longer names Iris stops startup too: CraftServer would build it
|
||||
* with the vanilla generator without ever asking Iris.
|
||||
* <p>
|
||||
* A world with no folder at all is not a startup failure: nothing enumerates it, nothing loads it, and
|
||||
* its bukkit.yml and Multiverse entries are what make restoring the folder a complete recovery. Neither
|
||||
* is a folder that holds no pack snapshot and no world data - {@link #quarantineWorthlessHusks} has
|
||||
* already moved those out of the dimensions tree, and one that survives it (a Spigot-layout world folder,
|
||||
* or a move that failed) owns nothing to lose. Both are only reported here.
|
||||
*/
|
||||
static void requireUsableWorldStorage(BukkitStartupPaths startupPaths) throws IOException {
|
||||
Path levelRoot = startupPaths.levelRoot();
|
||||
Path levelName = levelRoot.getFileName();
|
||||
if (levelName == null || levelName.toString().isBlank()) {
|
||||
throw new IOException("Configured level root has no startup level id: " + levelRoot);
|
||||
}
|
||||
List<IrisWorldStorageEntry> entries = BukkitWorldConfiguration.auditIrisWorldStorage(
|
||||
startupPaths.bukkitConfiguration().toFile(),
|
||||
levelName.toString(),
|
||||
levelRoot
|
||||
);
|
||||
StringBuilder unusable = new StringBuilder();
|
||||
StringBuilder unbound = new StringBuilder();
|
||||
for (IrisWorldStorageEntry entry : entries) {
|
||||
switch (entry.state()) {
|
||||
case PRESENT -> {
|
||||
}
|
||||
case MISSING -> MissingWorldStorageLog.warnOnce(
|
||||
entry.configuredWorldName(),
|
||||
entry.storagePath());
|
||||
case EMPTY -> MissingWorldStorageLog.warnEmptyOnce(
|
||||
entry.configuredWorldName(),
|
||||
entry.storagePath());
|
||||
case UNUSABLE -> unusable.append(unusable.isEmpty() ? "" : "; ")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(" (")
|
||||
.append(entry.storagePath())
|
||||
.append(": ")
|
||||
.append(entry.detail() == null ? "storage is unusable" : entry.detail())
|
||||
.append(')');
|
||||
case UNBOUND -> unbound.append(unbound.isEmpty() ? "" : "; ")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(" (")
|
||||
.append(entry.storagePath())
|
||||
.append("): set worlds.")
|
||||
.append(entry.configuredWorldName())
|
||||
.append(".generator to Iris:<pack> in bukkit.yml, or move the folder aside to start a new"
|
||||
+ " vanilla world there");
|
||||
}
|
||||
}
|
||||
List<String> refusals = new ArrayList<>(2);
|
||||
if (!unusable.isEmpty()) {
|
||||
refusals.add("Iris world storage is unusable and the server would generate vanilla terrain over it: "
|
||||
+ unusable + ". Restore each world folder from a backup, or move it aside; a world with no"
|
||||
+ " folder is reported and skipped, and the server starts.");
|
||||
}
|
||||
if (!unbound.isEmpty()) {
|
||||
refusals.add("Iris worlds in vanilla slots are not bound to Iris, so the server would generate vanilla"
|
||||
+ " terrain into them: " + unbound + ".");
|
||||
}
|
||||
if (!refusals.isEmpty()) {
|
||||
throw new IllegalStateException(String.join(" ", refusals));
|
||||
}
|
||||
}
|
||||
|
||||
static void armStartupFailure(BootstrapContext context, Throwable failure) {
|
||||
armStartupFailure(context, failure, LifecycleEvents.DATAPACK_DISCOVERY);
|
||||
}
|
||||
|
||||
static <E extends LifecycleEvent> void armStartupFailure(
|
||||
BootstrapContext context,
|
||||
Throwable failure,
|
||||
LifecycleEventType<? super BootstrapContext, ? extends E, ?> eventType
|
||||
) {
|
||||
context.getLifecycleManager().registerEventHandler(eventType, event -> {
|
||||
throw new IllegalStateException("Iris bootstrap did not establish safe world-generation state.", failure);
|
||||
});
|
||||
List<String> notice = startupRefusalNotice(failure);
|
||||
try {
|
||||
for (String line : notice) {
|
||||
context.getLogger().error(line);
|
||||
}
|
||||
context.getLogger().warn("Iris bootstrap failure", failure);
|
||||
} catch (Throwable loggingFailure) {
|
||||
notice.forEach(System.err::println);
|
||||
failure.addSuppressed(loggingFailure);
|
||||
failure.printStackTrace(System.err);
|
||||
}
|
||||
}
|
||||
|
||||
static List<String> startupRefusalNotice(Throwable failure) {
|
||||
return GenerationRefusalNotice.compose(
|
||||
"Iris stopped server startup before any world loads",
|
||||
GenerationRefusalNotice.causes(failure),
|
||||
List.of(
|
||||
"Startup stops at datapack discovery: no world loads and no chunks are written.",
|
||||
"Fix the cause, then start the server again. Paper's --safeMode hint does not apply:"
|
||||
+ " Iris worlds must not load without Iris."
|
||||
));
|
||||
}
|
||||
|
||||
private static ProvisionResult provision(BootstrapContext context, BukkitStartupPaths startupPaths) {
|
||||
try {
|
||||
return DefaultPackBootstrapProvisioner.provision(new BootstrapRequest(
|
||||
context.getDataDirectory(),
|
||||
message -> context.getLogger().info(message),
|
||||
startupPaths,
|
||||
DataVersion.forMinecraftVersion(ServerBuildInfo.buildInfo().minecraftVersionId())
|
||||
));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Unable to provision the Iris startup datapack", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
|
||||
import art.arcane.volmlib.integration.ReloadAware;
|
||||
import art.arcane.volmlib.util.function.NastyRunnable;
|
||||
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.server.PluginDisableEvent;
|
||||
import org.bukkit.event.server.PluginEnableEvent;
|
||||
import org.bukkit.generator.BiomeProvider;
|
||||
import org.bukkit.generator.ChunkGenerator;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
interface IrisPluginRuntime {
|
||||
static IrisPluginRuntime create(Iris plugin) {
|
||||
return new IrisRuntime(plugin);
|
||||
}
|
||||
|
||||
static void bootstrap(BootstrapContext context) {
|
||||
IrisBootstrapSequence.bootstrap(context);
|
||||
}
|
||||
|
||||
static VolmitSender getSender() {
|
||||
return IrisRuntime.getSender();
|
||||
}
|
||||
|
||||
static <T> T service(Class<T> type) {
|
||||
return IrisRuntime.service(type);
|
||||
}
|
||||
|
||||
static void callEvent(Event event) {
|
||||
IrisRuntime.callEvent(event);
|
||||
}
|
||||
|
||||
static void msg(String message) {
|
||||
IrisRuntime.msg(message);
|
||||
}
|
||||
|
||||
static void warn(String format, Object... args) {
|
||||
IrisRuntime.warn(format, args);
|
||||
}
|
||||
|
||||
static void error(String format, Object... args) {
|
||||
IrisRuntime.error(format, args);
|
||||
}
|
||||
|
||||
static void debug(String message) {
|
||||
IrisRuntime.debug(message);
|
||||
}
|
||||
|
||||
static void debug(String category, int line, String message) {
|
||||
IrisRuntime.debug(category, line, message);
|
||||
}
|
||||
|
||||
static void verbose(String message) {
|
||||
IrisRuntime.verbose(message);
|
||||
}
|
||||
|
||||
static void success(String message) {
|
||||
IrisRuntime.success(message);
|
||||
}
|
||||
|
||||
static void info(String format, Object... args) {
|
||||
IrisRuntime.info(format, args);
|
||||
}
|
||||
|
||||
static void later(NastyRunnable task) {
|
||||
IrisRuntime.later(task);
|
||||
}
|
||||
|
||||
static void reportErrorChunk(int x, int z, Throwable failure, String extra) {
|
||||
IrisRuntime.reportErrorChunk(x, z, failure, extra);
|
||||
}
|
||||
|
||||
static void reportError(Throwable failure) {
|
||||
IrisRuntime.reportError(failure);
|
||||
}
|
||||
|
||||
static void reportError(String context, Throwable failure) {
|
||||
IrisRuntime.reportError(context, failure);
|
||||
}
|
||||
|
||||
static void dump() {
|
||||
IrisRuntime.dump();
|
||||
}
|
||||
|
||||
static void panic() {
|
||||
IrisRuntime.panic();
|
||||
}
|
||||
|
||||
static String tag(String subTag) {
|
||||
return IrisRuntime.tag(subTag);
|
||||
}
|
||||
|
||||
void initialize();
|
||||
|
||||
void onEnable();
|
||||
|
||||
void onDisable();
|
||||
|
||||
CompletionStage<Void> commitReload(ReloadAware.PreUnloadReason reason);
|
||||
|
||||
void selectLanguage(CommandSender sender, String[] arguments);
|
||||
|
||||
List<String> completeLanguage(CommandSender sender, String[] arguments);
|
||||
|
||||
void onPlaceholderApiEnable(PluginEnableEvent event);
|
||||
|
||||
void onPlaceholderApiDisable(PluginDisableEvent event);
|
||||
|
||||
BiomeProvider getDefaultBiomeProvider(String worldName, String id);
|
||||
|
||||
ChunkGenerator getDefaultWorldGenerator(String worldName, String id);
|
||||
|
||||
ChunkGenerator requireWorldGenerator(String worldName, String id);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.command;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.localization.BukkitCommandMessagesExtended;
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
@@ -19,7 +20,7 @@ public final class CommandDebug implements DirectorExecutor {
|
||||
@Param(name = "upload", defaultValue = "true", description = "Upload the report to mclo.gs", descriptionKey = "iris.director.commandiris.param.debugdump_upload") boolean upload,
|
||||
@Param(name = "sender", contextual = true) CommandSender sender
|
||||
) {
|
||||
Iris.instance.debugDump().request(sender, upload);
|
||||
IrisRuntime.require().debugDump().request(sender, upload);
|
||||
}
|
||||
|
||||
@Director(sync = true, description = "Print version information", descriptionKey = "iris.director.commandiris.director.print_version_information")
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris.command;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.iris.world.BukkitWorldReconciler;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
@@ -216,7 +217,7 @@ public class CommandIris implements DirectorExecutor {
|
||||
) {
|
||||
NamespacedKey worldKey;
|
||||
try {
|
||||
worldKey = Iris.instance.pendingWorldReplacements().resolveRequestedWorldKey(target);
|
||||
worldKey = IrisRuntime.require().pendingWorldReplacements().resolveRequestedWorldKey(target);
|
||||
} catch (IllegalArgumentException e) {
|
||||
sender().sendMessage(C.RED + e.getMessage());
|
||||
return;
|
||||
@@ -240,7 +241,7 @@ public class CommandIris implements DirectorExecutor {
|
||||
}
|
||||
|
||||
try {
|
||||
PendingWorldReplacementManager.StagedReplacement staged = Iris.instance
|
||||
PendingWorldReplacementManager.StagedReplacement staged = IrisRuntime.require()
|
||||
.pendingWorldReplacements()
|
||||
.stageReplacement(sender(), worldKey, dimension, seed);
|
||||
String seedDetail = seed == null
|
||||
@@ -634,7 +635,7 @@ public class CommandIris implements DirectorExecutor {
|
||||
|
||||
VolmitSender responseSender = sender();
|
||||
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_LOADING_WORLD, MessageArgument.untrusted("logicalWorldName", logicalWorldName)));
|
||||
Iris.instance.worldReconciler()
|
||||
IrisRuntime.require().worldReconciler()
|
||||
.loadWorld(BUKKIT_YML, worldKey.toString())
|
||||
.whenComplete((result, failure) -> {
|
||||
Runnable response = () -> reportLoadWorldResult(
|
||||
|
||||
@@ -27,6 +27,8 @@ import org.bukkit.Particle;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.World;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.iris.platform.bukkit.chunk.TicketHolder;
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
import art.arcane.iris.localization.RuntimeUiMessages;
|
||||
import art.arcane.iris.studio.edit.DustRevealer;
|
||||
@@ -109,7 +111,7 @@ public class WandSVC implements IrisService {
|
||||
|
||||
int total = c.getSizeX() * c.getSizeY() * c.getSizeZ();
|
||||
var latch = new CountDownLatch(1);
|
||||
var holder = Iris.tickets.getHolder(p.getWorld());
|
||||
TicketHolder holder = IrisRuntime.require().tickets().getHolder(p.getWorld());
|
||||
new Job() {
|
||||
private volatile int i;
|
||||
private Chunk chunk;
|
||||
|
||||
+7
-7
@@ -68,8 +68,8 @@ public final class BukkitWorldReconciler {
|
||||
private final Backend backend;
|
||||
private final LifecycleOperationCoordinator coordinator;
|
||||
|
||||
public BukkitWorldReconciler(Iris plugin) {
|
||||
this(new BukkitBackend(plugin), LifecycleOperationCoordinator.get());
|
||||
public BukkitWorldReconciler(IrisWorldGeneratorResolver generatorResolver) {
|
||||
this(new BukkitBackend(generatorResolver), LifecycleOperationCoordinator.get());
|
||||
}
|
||||
|
||||
BukkitWorldReconciler(Backend backend, LifecycleOperationCoordinator coordinator) {
|
||||
@@ -688,10 +688,10 @@ public final class BukkitWorldReconciler {
|
||||
}
|
||||
|
||||
private static final class BukkitBackend implements Backend {
|
||||
private final Iris plugin;
|
||||
private final IrisWorldGeneratorResolver generatorResolver;
|
||||
|
||||
private BukkitBackend(Iris plugin) {
|
||||
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
||||
private BukkitBackend(IrisWorldGeneratorResolver generatorResolver) {
|
||||
this.generatorResolver = Objects.requireNonNull(generatorResolver, "generatorResolver");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -734,13 +734,13 @@ public final class BukkitWorldReconciler {
|
||||
try {
|
||||
configuredWorldName = configuredWorldName(worldKey);
|
||||
Iris.info("Loading World: %s | Generator: %s", IrisWorldStorage.logicalName(worldKey), dimension);
|
||||
generator = plugin.requireWorldGenerator(configuredWorldName, dimension);
|
||||
generator = generatorResolver.requireWorldGenerator(configuredWorldName, dimension);
|
||||
irisDimension = IrisWorldGeneratorResolver.loadDimension(configuredWorldName, dimension);
|
||||
if (generator == null || irisDimension == null) {
|
||||
throw new IllegalStateException("Could not resolve the Iris generator or dimension \"" + dimension + "\".");
|
||||
}
|
||||
} catch (Throwable refusal) {
|
||||
plugin.worldRefusals().report(configuredWorldName, worldKey, refusal);
|
||||
generatorResolver.refusals().report(configuredWorldName, worldKey, refusal);
|
||||
return CompletableFuture.failedFuture(refusal);
|
||||
}
|
||||
try {
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package art.arcane.iris.fixture;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.volmlib.nativelib.NativeAdapters;
|
||||
import art.arcane.iris.world.runtime.RuntimeInjection;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
@@ -138,7 +138,7 @@ public final class NativeLifecycleFixture extends JavaPlugin implements WorldRun
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
if (WorldCreatorCompat.persistentLevelRoot(TREASURE_KEY).exists()) {
|
||||
return Iris.instance.worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString());
|
||||
return IrisRuntime.require().worldReconciler().loadWorld(ServerProperties.BUKKIT_YML, TREASURE_KEY.toString());
|
||||
}
|
||||
return runAsync(() -> {
|
||||
try {
|
||||
|
||||
@@ -148,16 +148,16 @@ public class FailedEnableLockTest {
|
||||
try (EnableFixture fixture = new EnableFixture(false)) {
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, plugin::onEnable);
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("already bound"));
|
||||
Field failed = Iris.class.getDeclaredField("enableFailed");
|
||||
Field failed = IrisRuntime.class.getDeclaredField("enableFailed");
|
||||
failed.setAccessible(true);
|
||||
assertTrue(failed.getBoolean(plugin));
|
||||
assertTrue(failed.getBoolean(plugin.runtime()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void anUnsupportedServerWithIrisWorldsLocksInsteadOfDisablingIris() throws Exception {
|
||||
Iris plugin = plugin();
|
||||
set(plugin, "pendingWorldReplacements", mock(PendingWorldReplacementManager.class));
|
||||
set(IrisRuntime.class, plugin.runtime(), "pendingWorldReplacements", mock(PendingWorldReplacementManager.class));
|
||||
|
||||
try (EnableFixture fixture = new EnableFixture(true);
|
||||
MockedStatic<INMS> nms = mockStatic(INMS.class);
|
||||
@@ -208,18 +208,18 @@ public class FailedEnableLockTest {
|
||||
|
||||
/**
|
||||
* Paper builds plugins through its class loader, so the plugin under test is the real class with its fields
|
||||
* set by hand: the resolver getDefaultWorldGenerator delegates to, and whatever enable touches before failing.
|
||||
* set by hand: the runtime getDefaultWorldGenerator delegates to, and whatever enable touches before failing.
|
||||
*/
|
||||
private static Iris plugin() throws Exception {
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
set(plugin, "generatorResolver", new IrisWorldGeneratorResolver(plugin));
|
||||
set(Iris.class, plugin, "runtime", new IrisRuntime(plugin));
|
||||
return plugin;
|
||||
}
|
||||
|
||||
private static void set(Iris plugin, String name, Object value) throws Exception {
|
||||
Field field = Iris.class.getDeclaredField(name);
|
||||
private static void set(Class<?> owner, Object target, String name, Object value) throws Exception {
|
||||
Field field = owner.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(plugin, value);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -11,8 +11,8 @@ import static org.junit.Assert.assertTrue;
|
||||
public class IrisApiServiceDiscoveryTest {
|
||||
@Test
|
||||
public void bothApiServicesSatisfyTheServiceLoaderRule() {
|
||||
assertTrue(Iris.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class));
|
||||
assertTrue(Iris.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class));
|
||||
assertTrue(IrisRuntime.isConcreteImplementation(IrisTerrainSVC.class, IrisService.class));
|
||||
assertTrue(IrisRuntime.isConcreteImplementation(IrisApiEventSVC.class, IrisService.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ public class IrisBootstrapFailureContractTest {
|
||||
when(context.getLogger()).thenReturn(logger);
|
||||
when(context.getLifecycleManager()).thenReturn(manager);
|
||||
|
||||
IrisBootstrap.armStartupFailure(context, cause, eventType);
|
||||
IrisBootstrapSequence.armStartupFailure(context, cause, eventType);
|
||||
|
||||
assertSame(eventType, manager.eventType);
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, manager::runCapturedHandler);
|
||||
@@ -47,7 +47,7 @@ public class IrisBootstrapFailureContractTest {
|
||||
IllegalStateException failure = new IllegalStateException("Iris world storage is unusable",
|
||||
new IOException("Invalid generation manifest: manifest.json"));
|
||||
|
||||
IrisBootstrap.armStartupFailure(context, failure, lifecycleEventType());
|
||||
IrisBootstrapSequence.armStartupFailure(context, failure, lifecycleEventType());
|
||||
|
||||
ArgumentCaptor<String> lines = ArgumentCaptor.forClass(String.class);
|
||||
verify(logger, atLeastOnce()).error(lines.capture());
|
||||
|
||||
+15
-15
@@ -44,7 +44,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
|
||||
IllegalStateException failure = assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("world_iris_orphan2"));
|
||||
assertTrue(failure.getMessage(),
|
||||
@@ -64,7 +64,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeServerProperties(serverRoot);
|
||||
writeBukkitWorlds(serverRoot, "world_iris_husk");
|
||||
|
||||
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
|
||||
assertTrue(MissingWorldStorageLog.hasWarned("world_iris_husk"));
|
||||
}
|
||||
@@ -83,8 +83,8 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeBukkitWorlds(serverRoot, "world_iris_husk");
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
|
||||
assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk")));
|
||||
assertEquals(1, warnings.size());
|
||||
@@ -106,7 +106,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeBukkitWorlds(serverRoot);
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
|
||||
assertFalse(Files.exists(serverRoot.resolve("world/dimensions/iris/husk")));
|
||||
assertEquals(1, warnings.size());
|
||||
@@ -121,13 +121,13 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeBukkitWorlds(serverRoot, "world_iris_kept");
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
|
||||
assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/kept")));
|
||||
assertTrue(warnings.isEmpty());
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -142,13 +142,13 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeBukkitWorlds(serverRoot, "world_iris_marked");
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
IrisBootstrap.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
IrisBootstrapSequence.quarantineWorthlessHusks(startupPaths(serverRoot), warnings::add);
|
||||
|
||||
assertTrue(Files.isDirectory(serverRoot.resolve("world/dimensions/iris/marked/iris/engine-data")));
|
||||
assertTrue(warnings.isEmpty());
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -158,7 +158,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeServerProperties(serverRoot);
|
||||
writeBukkitWorlds(serverRoot, "world_iris_orphan1");
|
||||
|
||||
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
|
||||
assertTrue(MissingWorldStorageLog.hasWarned("world_iris_orphan1"));
|
||||
}
|
||||
@@ -170,7 +170,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeServerProperties(serverRoot);
|
||||
writeBukkitWorlds(serverRoot, "world_iris_moon");
|
||||
|
||||
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
|
||||
assertFalse(MissingWorldStorageLog.hasWarned("world_iris_moon"));
|
||||
}
|
||||
@@ -190,7 +190,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
|
||||
IllegalStateException failure = assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
|
||||
assertTrue(failure.getMessage(),
|
||||
failure.getMessage().contains(serverRoot.toRealPath().resolve("world/dimensions/minecraft/overworld")
|
||||
@@ -210,7 +210,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
|
||||
IllegalStateException failure = assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("Invalid generation manifest"));
|
||||
assertFalse(failure.getMessage(), failure.getMessage().contains("\n"));
|
||||
@@ -229,7 +229,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
|
||||
IllegalStateException failure = assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
() -> IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot)));
|
||||
|
||||
assertTrue(failure.getMessage(), failure.getMessage().contains("worlds.world.generator"));
|
||||
assertTrue(failure.getMessage(),
|
||||
@@ -247,7 +247,7 @@ public class IrisBootstrapWorldStorageContractTest {
|
||||
writeServerProperties(serverRoot);
|
||||
writeBukkitWorlds(serverRoot);
|
||||
|
||||
IrisBootstrap.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
IrisBootstrapSequence.requireUsableWorldStorage(startupPaths(serverRoot));
|
||||
}
|
||||
|
||||
private static BukkitStartupPaths startupPaths(Path serverRoot) throws Exception {
|
||||
|
||||
+5
-5
@@ -15,18 +15,18 @@ import static org.junit.Assert.assertNull;
|
||||
public class IrisDiagnosticLogLevelTest {
|
||||
@Test
|
||||
public void coreDiagnosticsKeepTheirSeverity() {
|
||||
assertEquals(Level.WARNING, Iris.diagnosticLevel(LogLevel.WARN));
|
||||
assertEquals(Level.SEVERE, Iris.diagnosticLevel(LogLevel.ERROR));
|
||||
assertEquals(Level.WARNING, IrisRuntime.diagnosticLevel(LogLevel.WARN));
|
||||
assertEquals(Level.SEVERE, IrisRuntime.diagnosticLevel(LogLevel.ERROR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void informationalAndDebugMessagesStayOnTheInformationalPath() {
|
||||
assertNull(Iris.diagnosticLevel(LogLevel.INFO));
|
||||
assertNull(Iris.diagnosticLevel(LogLevel.DEBUG));
|
||||
assertNull(IrisRuntime.diagnosticLevel(LogLevel.INFO));
|
||||
assertNull(IrisRuntime.diagnosticLevel(LogLevel.DEBUG));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lifecycleNoticesReachThePluginLoggerAtInfo() {
|
||||
assertEquals(Level.INFO, Iris.diagnosticLevel(LogLevel.NOTICE));
|
||||
assertEquals(Level.INFO, IrisRuntime.diagnosticLevel(LogLevel.NOTICE));
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,8 @@ public class IrisDiagnosticsTest {
|
||||
public void serviceInitializationSkipsPackageHelperClasses() throws Exception {
|
||||
Class<?> registrar = Class.forName("art.arcane.iris.command.PaperCommandRegistrar");
|
||||
|
||||
assertFalse(Iris.isConcreteImplementation(registrar, IrisService.class));
|
||||
assertTrue(Iris.isConcreteImplementation(CommandSVC.class, IrisService.class));
|
||||
assertFalse(IrisRuntime.isConcreteImplementation(registrar, IrisService.class));
|
||||
assertTrue(IrisRuntime.isConcreteImplementation(CommandSVC.class, IrisService.class));
|
||||
// The service package is eagerly Class.forName-scanned by JarScanner at enable; a class
|
||||
// referencing Paper-only types there prints an NCDFE stack trace on plain Spigot.
|
||||
assertFalse(
|
||||
|
||||
@@ -9,10 +9,8 @@ import org.mockito.MockedStatic;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
@@ -53,9 +51,6 @@ public class IrisErrorReportingTest {
|
||||
IrisSettings previousSettings = IrisSettings.settings;
|
||||
PrintStream previousError = System.err;
|
||||
Iris plugin = mock(Iris.class);
|
||||
Field deferred = Iris.class.getDeclaredField("serverStopTeardownDeferred");
|
||||
deferred.setAccessible(true);
|
||||
deferred.set(plugin, new AtomicBoolean());
|
||||
File report = new File(temporaryFolder.getRoot(), "failure.txt");
|
||||
when(plugin.getDataFile(any(String[].class))).thenReturn(report);
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
|
||||
+46
-46
@@ -10,7 +10,6 @@ import art.arcane.iris.platform.bukkit.plugin.IrisService;
|
||||
import art.arcane.iris.platform.bukkit.plugin.VolmitPlugin;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.world.lifecycle.IrisRuntimeStatics;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.iris.generation.runtime.GenerationSessionLease;
|
||||
import art.arcane.iris.generation.runtime.GenerationSessionManager;
|
||||
@@ -38,6 +37,7 @@ import org.mockito.MockedStatic;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
@@ -84,7 +84,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
return false;
|
||||
});
|
||||
setField(fixture.plugin, "serverShutdownBoundary", boundary);
|
||||
setField(fixture.runtime, "serverShutdownBoundary", boundary);
|
||||
fixture.quiesce();
|
||||
fixture.startFinisher();
|
||||
try {
|
||||
@@ -108,9 +108,9 @@ public class IrisShutdownMaintenanceTest {
|
||||
@Test
|
||||
public void missingShutdownBoundaryDoesNotAuthorizeResourceRelease() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Method method = Iris.class.getDeclaredMethod("awaitServerShutdownBoundary");
|
||||
Method method = IrisRuntime.class.getDeclaredMethod("awaitServerShutdownBoundary");
|
||||
method.setAccessible(true);
|
||||
assertEquals(false, method.invoke(fixture.plugin));
|
||||
assertEquals(false, method.invoke(fixture.runtime));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
assertSame(fixture.plugin.getClass().getClassLoader(), invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
|
||||
invoke(fixture.plugin, "initializeShutdownProtection");
|
||||
invoke(fixture.runtime, "initializeShutdownProtection");
|
||||
verify(fixture.binding).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
|
||||
verify(fixture.binding, never()).injectBukkit();
|
||||
}
|
||||
@@ -190,7 +190,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
try (Fixture fixture = new Fixture(); MockedStatic<Agent> agent = mockStatic(Agent.class)) {
|
||||
when(fixture.binding.supportsIrisWorldGeneration()).thenReturn(true);
|
||||
InvocationTargetException failure = assertThrows(InvocationTargetException.class,
|
||||
() -> invoke(fixture.plugin, "initializeShutdownProtection"));
|
||||
() -> invoke(fixture.runtime, "initializeShutdownProtection"));
|
||||
assertTrue(failure.getCause() instanceof IllegalStateException);
|
||||
verify(fixture.binding, never()).initializeLifecycle(fixture.plugin.getClass().getClassLoader());
|
||||
}
|
||||
@@ -208,8 +208,8 @@ public class IrisShutdownMaintenanceTest {
|
||||
IllegalStateException failure = new IllegalStateException("world hook teardown failed");
|
||||
fixture.nms.when(INMS::isBound).thenReturn(true);
|
||||
doThrow(failure).when(fixture.binding).uninjectBukkit();
|
||||
setField(fixture.plugin, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.plugin, "enabledServices", List.of(service));
|
||||
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.runtime, "enabledServices", List.of(service));
|
||||
doAnswer(invocation -> {
|
||||
platforms.verify(IrisPlatforms::unbind);
|
||||
bukkitPlatform.verify(BukkitPlatform::releaseHost);
|
||||
@@ -257,8 +257,8 @@ public class IrisShutdownMaintenanceTest {
|
||||
IrisService service = mock(IrisService.class);
|
||||
IllegalStateException failure = new IllegalStateException("service teardown failed");
|
||||
doThrow(failure).when(service).onDisable();
|
||||
setField(fixture.plugin, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.plugin, "enabledServices", List.of(service));
|
||||
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.runtime, "enabledServices", List.of(service));
|
||||
fixture.quiesce();
|
||||
fixture.finish(5L);
|
||||
verify(service).onDisable();
|
||||
@@ -293,7 +293,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
IllegalStateException failure = new IllegalStateException("post-shutdown callback failed");
|
||||
AtomicBoolean cleanupAttempted = new AtomicBoolean();
|
||||
KList<Runnable> callbacks = new KList<>();
|
||||
List<Runnable> callbacks = new ArrayList<>();
|
||||
callbacks.add(() -> { throw failure; });
|
||||
callbacks.add(() -> {
|
||||
cleanupAttempted.set(true);
|
||||
@@ -302,9 +302,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
Field callbacksField = VolmitPlugin.class.getDeclaredField("postShutdown");
|
||||
callbacksField.setAccessible(true);
|
||||
callbacksField.set(fixture.plugin, callbacks);
|
||||
Method runCallbacks = VolmitPlugin.class.getDeclaredMethod("runPostShutdown");
|
||||
runCallbacks.setAccessible(true);
|
||||
runCallbacks.invoke(doCallRealMethod().when(fixture.plugin));
|
||||
doCallRealMethod().when(fixture.plugin).runPostShutdown();
|
||||
fixture.quiesce();
|
||||
fixture.finish(5L);
|
||||
iris.verify(() -> Iris.reportError("Failed to run Iris post-shutdown cleanup.", failure));
|
||||
@@ -326,8 +324,8 @@ public class IrisShutdownMaintenanceTest {
|
||||
public void incompleteDrainRetainsServicesWorkersAndClassLoader() throws Exception {
|
||||
try (Fixture fixture = new Fixture(); MockedStatic<Iris> iris = mockStatic(Iris.class)) {
|
||||
IrisService service = mock(IrisService.class);
|
||||
setField(fixture.plugin, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.plugin, "enabledServices", List.of(service));
|
||||
setField(fixture.runtime, "services", new KMap<Class<? extends IrisService>, IrisService>());
|
||||
setField(fixture.runtime, "enabledServices", List.of(service));
|
||||
when(fixture.generator.closeAsync()).thenReturn(new CompletableFuture<>());
|
||||
fixture.quiesce();
|
||||
fixture.finish(0L);
|
||||
@@ -340,7 +338,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
@Test
|
||||
public void serverStopPreUnloadDefersTeardownWhileTheClassLoaderIsHeld() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
setField(fixture.plugin, "postStopFinisherStarted", new AtomicBoolean(true));
|
||||
setField(fixture.runtime, "postStopFinisherStarted", new AtomicBoolean(true));
|
||||
try {
|
||||
fixture.commitReloadDuringServerStop();
|
||||
verify(fixture.binding).deferPluginClassLoaderClose();
|
||||
@@ -373,7 +371,7 @@ public class IrisShutdownMaintenanceTest {
|
||||
@Test
|
||||
public void serverStopPreUnloadDrainsInlineWithoutInitializedProtection() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
setField(fixture.plugin, "shutdownProtectionInitialized", false);
|
||||
setField(fixture.runtime, "shutdownProtectionInitialized", false);
|
||||
try {
|
||||
fixture.commitReloadDuringServerStop();
|
||||
verify(fixture.binding, never()).deferPluginClassLoaderClose();
|
||||
@@ -386,20 +384,21 @@ public class IrisShutdownMaintenanceTest {
|
||||
}
|
||||
}
|
||||
|
||||
private static void invoke(Iris plugin, String name) throws ReflectiveOperationException {
|
||||
Method method = Iris.class.getDeclaredMethod(name);
|
||||
private static void invoke(IrisRuntime runtime, String name) throws ReflectiveOperationException {
|
||||
Method method = IrisRuntime.class.getDeclaredMethod(name);
|
||||
method.setAccessible(true);
|
||||
method.invoke(plugin);
|
||||
method.invoke(runtime);
|
||||
}
|
||||
|
||||
private static void setField(Iris plugin, String name, Object value) throws ReflectiveOperationException {
|
||||
Field field = Iris.class.getDeclaredField(name);
|
||||
private static void setField(IrisRuntime runtime, String name, Object value) throws ReflectiveOperationException {
|
||||
Field field = IrisRuntime.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(plugin, value);
|
||||
field.set(runtime, value);
|
||||
}
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
private final Iris plugin = mock(Iris.class);
|
||||
private final IrisRuntime runtime = mock(IrisRuntime.class);
|
||||
private final World world = mock(World.class);
|
||||
private final IrisWorld irisWorld = mock(IrisWorld.class);
|
||||
private final Engine engine = mock(Engine.class);
|
||||
@@ -419,15 +418,16 @@ public class IrisShutdownMaintenanceTest {
|
||||
|
||||
private Fixture() throws ReflectiveOperationException {
|
||||
IrisSettings.settings = new IrisSettings();
|
||||
setField(plugin, "shutdownProtectionInitialized", true);
|
||||
setField(plugin, "alreadyDrained", new AtomicBoolean());
|
||||
setField(plugin, "servicesDisabled", new AtomicBoolean());
|
||||
setField(plugin, "runtimeTeardownFailed", new AtomicBoolean());
|
||||
setField(plugin, "sharedRuntimeClosed", new AtomicBoolean());
|
||||
setField(plugin, "terminalCleanupCompleted", new AtomicBoolean());
|
||||
setField(plugin, "serverStopTeardownDeferred", new AtomicBoolean());
|
||||
setField(plugin, "postStopFinisherStarted", new AtomicBoolean());
|
||||
setField(plugin, "deferredShutdownGenerators", new CopyOnWriteArrayList<PlatformChunkGenerator>());
|
||||
setField(runtime, "plugin", plugin);
|
||||
setField(runtime, "shutdownProtectionInitialized", true);
|
||||
setField(runtime, "alreadyDrained", new AtomicBoolean());
|
||||
setField(runtime, "servicesDisabled", new AtomicBoolean());
|
||||
setField(runtime, "runtimeTeardownFailed", new AtomicBoolean());
|
||||
setField(runtime, "sharedRuntimeClosed", new AtomicBoolean());
|
||||
setField(runtime, "terminalCleanupCompleted", new AtomicBoolean());
|
||||
setField(runtime, "serverStopTeardownDeferred", new AtomicBoolean());
|
||||
setField(runtime, "postStopFinisherStarted", new AtomicBoolean());
|
||||
setField(runtime, "deferredShutdownGenerators", new CopyOnWriteArrayList<PlatformChunkGenerator>());
|
||||
when(world.getKey()).thenReturn(NamespacedKey.fromString(identity));
|
||||
when(engine.getWorld()).thenReturn(irisWorld);
|
||||
when(irisWorld.hasPlatformWorld()).thenReturn(true);
|
||||
@@ -441,42 +441,42 @@ public class IrisShutdownMaintenanceTest {
|
||||
}
|
||||
|
||||
private void quiesce() throws ReflectiveOperationException {
|
||||
Method method = Iris.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class);
|
||||
Method method = IrisRuntime.class.getDeclaredMethod("quiesceRuntimeForServerShutdown", String.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(plugin, "server_stop");
|
||||
method.invoke(runtime, "server_stop");
|
||||
quiesces++;
|
||||
}
|
||||
|
||||
private void drain() throws ReflectiveOperationException {
|
||||
Method method = Iris.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class);
|
||||
Method method = IrisRuntime.class.getDeclaredMethod("drainWorldGenerators", String.class, long.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(plugin, "manual_disable", 5L);
|
||||
method.invoke(runtime, "manual_disable", 5L);
|
||||
}
|
||||
|
||||
private void commitReloadDuringServerStop() throws ReflectiveOperationException {
|
||||
setField(plugin, "alreadyDrained", new AtomicBoolean());
|
||||
setField(runtime, "alreadyDrained", new AtomicBoolean());
|
||||
toolbelt.when(IrisToolbelt::isServerStopping).thenReturn(true);
|
||||
doCallRealMethod().when(plugin).commitReload(any());
|
||||
plugin.commitReload(ReloadAware.PreUnloadReason.HOT_UNLOAD);
|
||||
doCallRealMethod().when(runtime).commitReload(any());
|
||||
runtime.commitReload(ReloadAware.PreUnloadReason.HOT_UNLOAD);
|
||||
}
|
||||
|
||||
private boolean serverStopTeardownDeferred() throws ReflectiveOperationException {
|
||||
Field field = Iris.class.getDeclaredField("serverStopTeardownDeferred");
|
||||
Field field = IrisRuntime.class.getDeclaredField("serverStopTeardownDeferred");
|
||||
field.setAccessible(true);
|
||||
return ((AtomicBoolean) field.get(plugin)).get();
|
||||
return ((AtomicBoolean) field.get(runtime)).get();
|
||||
}
|
||||
|
||||
|
||||
private void finish(long timeoutSeconds) throws ReflectiveOperationException {
|
||||
Method method = Iris.class.getDeclaredMethod("finishDeferredRuntimeTeardown", String.class, long.class);
|
||||
Method method = IrisRuntime.class.getDeclaredMethod("finishDeferredRuntimeTeardown", String.class, long.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(plugin, "test_shutdown", timeoutSeconds);
|
||||
method.invoke(runtime, "test_shutdown", timeoutSeconds);
|
||||
}
|
||||
|
||||
private void startFinisher() throws ReflectiveOperationException {
|
||||
Method method = Iris.class.getDeclaredMethod("startPostStopFinisher");
|
||||
Method method = IrisRuntime.class.getDeclaredMethod("startPostStopFinisher");
|
||||
method.setAccessible(true);
|
||||
method.invoke(plugin);
|
||||
method.invoke(runtime);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -11,16 +11,13 @@ import java.util.List;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Answers.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
|
||||
public class IrisVersionNumberTest {
|
||||
@Test
|
||||
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
|
||||
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
|
||||
assertEquals(version, 433, plugin(version).getIrisVersion());
|
||||
assertEquals(version, 433, IrisRuntime.irisVersion(version));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,10 +26,8 @@ public class IrisVersionNumberTest {
|
||||
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
|
||||
assertNotNull(stream);
|
||||
PluginDescriptionFile description = new PluginDescriptionFile(stream);
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(description).when(plugin).getDescription();
|
||||
|
||||
assertNotEquals(-1, plugin.getIrisVersion());
|
||||
assertNotEquals(-1, IrisRuntime.irisVersion(description.getVersion()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,28 +35,21 @@ public class IrisVersionNumberTest {
|
||||
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
|
||||
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
|
||||
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
|
||||
assertEquals(version, -1, plugin(version).getIrisVersion());
|
||||
assertEquals(version, -1, IrisRuntime.irisVersion(version));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportedMinecraftVersionsRetainTheirEngineNumbers() {
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
try (MockedStatic<Bukkit> bukkit = mockStatic(Bukkit.class)) {
|
||||
bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-74-ver/26.1.2@e4e17fc (MC: 26.1.2)");
|
||||
assertEquals(2612, plugin.getMCVersion());
|
||||
assertEquals(2612, IrisRuntime.minecraftVersion());
|
||||
bukkit.when(Bukkit::getVersion).thenReturn("26.1.2-8-ver/26.1.x@62dc0f2 (MC: 26.1.2)");
|
||||
assertEquals(2612, plugin.getMCVersion());
|
||||
assertEquals(2612, IrisRuntime.minecraftVersion());
|
||||
bukkit.when(Bukkit::getVersion).thenReturn("26.2-133 (MC: 26.2)");
|
||||
assertEquals(262, plugin.getMCVersion());
|
||||
assertEquals(262, IrisRuntime.minecraftVersion());
|
||||
bukkit.when(Bukkit::getVersion).thenReturn("26.3-169 (MC: 26.3)");
|
||||
assertEquals(263, plugin.getMCVersion());
|
||||
assertEquals(263, IrisRuntime.minecraftVersion());
|
||||
}
|
||||
}
|
||||
|
||||
private static Iris plugin(String version) {
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.command;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.iris.command.CommandSVC;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import art.arcane.volmlib.util.diagnostics.BukkitDebugDump;
|
||||
@@ -30,18 +31,18 @@ import static org.mockito.Mockito.when;
|
||||
public class CommandDebugTest {
|
||||
@Test
|
||||
public void nestedDumpPreservesUploadDefaultAndLocalOnlyOption() {
|
||||
Iris previousPlugin = Iris.instance;
|
||||
Iris plugin = mock(Iris.class);
|
||||
Iris.instance = plugin;
|
||||
IrisRuntime runtime = mock(IrisRuntime.class);
|
||||
BukkitDebugDump dump = mock(BukkitDebugDump.class);
|
||||
CommandSender sender = mock(CommandSender.class);
|
||||
DirectorSender invocationSender = mock(DirectorSender.class);
|
||||
when(plugin.debugDump()).thenReturn(dump);
|
||||
when(runtime.debugDump()).thenReturn(dump);
|
||||
when(invocationSender.getName()).thenReturn("Console");
|
||||
DirectorContextRegistry contexts = new DirectorContextRegistry();
|
||||
contexts.register(CommandSender.class, (invocation, arguments) -> sender);
|
||||
|
||||
try (MockedStatic<Iris> iris = mockStatic(Iris.class)) {
|
||||
try (MockedStatic<Iris> iris = mockStatic(Iris.class);
|
||||
MockedStatic<IrisRuntime> runtimes = mockStatic(IrisRuntime.class)) {
|
||||
runtimes.when(IrisRuntime::require).thenReturn(runtime);
|
||||
DirectorRuntimeEngine engine = DirectorEngineFactory.create(new CommandIris(),
|
||||
DirectorEngineOptions.builder().contexts(contexts).build());
|
||||
|
||||
@@ -52,8 +53,6 @@ public class CommandDebugTest {
|
||||
assertEquals(List.of("dump", "toggle", "version"),
|
||||
DirectorMiniMenu.resolveHelp(engine, List.of("debug")).orElseThrow().entries().stream()
|
||||
.map(entry -> entry.getDescriptor().getName()).sorted().toList());
|
||||
} finally {
|
||||
Iris.instance = previousPlugin;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-3
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.integration;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.IrisRuntime;
|
||||
import art.arcane.volmlib.util.bukkit.papi.PlaceholderRegistration;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.HandlerList;
|
||||
@@ -89,12 +90,21 @@ public class IrisPapiLifecycleTest {
|
||||
when(iris.getLogger()).thenReturn(Logger.getAnonymousLogger());
|
||||
doCallRealMethod().when(iris).onPlaceholderApiEnable(any());
|
||||
doCallRealMethod().when(iris).onPlaceholderApiDisable(any());
|
||||
Field lifecycle = Iris.class.getDeclaredField("papiLifecycleActive");
|
||||
lifecycle.setAccessible(true);
|
||||
lifecycle.setBoolean(iris, active);
|
||||
IrisRuntime runtime = mock(IrisRuntime.class);
|
||||
doCallRealMethod().when(runtime).onPlaceholderApiEnable(any());
|
||||
doCallRealMethod().when(runtime).onPlaceholderApiDisable(any());
|
||||
set(IrisRuntime.class, runtime, "plugin", iris);
|
||||
set(IrisRuntime.class, runtime, "papiLifecycleActive", active);
|
||||
set(Iris.class, iris, "runtime", runtime);
|
||||
return iris;
|
||||
}
|
||||
|
||||
private static void set(Class<?> owner, Object target, String name, Object value) throws ReflectiveOperationException {
|
||||
Field field = owner.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
private static Plugin namedPlugin(String name) {
|
||||
Plugin plugin = mock(Plugin.class);
|
||||
when(plugin.getName()).thenReturn(name);
|
||||
|
||||
+8
-8
@@ -107,10 +107,10 @@ public class BukkitWorldReconcilerRuntimeTest {
|
||||
public void aRefusedReconcilerCreateIsReportedAsARefusal() throws Exception {
|
||||
NamespacedKey key = new NamespacedKey("iris", "probe");
|
||||
IllegalStateException refusal = new IllegalStateException("Iris generation history is unusable at /srv/probe.");
|
||||
Iris plugin = mock(Iris.class);
|
||||
IrisWorldGeneratorResolver resolver = mock(IrisWorldGeneratorResolver.class);
|
||||
WorldRefusalReporter refusals = mock(WorldRefusalReporter.class);
|
||||
when(plugin.worldRefusals()).thenReturn(refusals);
|
||||
when(plugin.requireWorldGenerator("world_iris_probe", "overworld")).thenThrow(refusal);
|
||||
when(resolver.refusals()).thenReturn(refusals);
|
||||
when(resolver.requireWorldGenerator("world_iris_probe", "overworld")).thenThrow(refusal);
|
||||
|
||||
try (MockedStatic<Iris> iris = mockStatic(Iris.class);
|
||||
MockedStatic<IrisWorldStorage> storage = mockStatic(IrisWorldStorage.class)) {
|
||||
@@ -118,7 +118,7 @@ public class BukkitWorldReconcilerRuntimeTest {
|
||||
storage.when(() -> IrisWorldStorage.configuredWorldName(key, "world")).thenReturn("world_iris_probe");
|
||||
storage.when(() -> IrisWorldStorage.logicalName(key)).thenReturn("probe");
|
||||
|
||||
CompletableFuture<World> created = backend(plugin).createWorld(key, "overworld", 1337L);
|
||||
CompletableFuture<World> created = backend(resolver).createWorld(key, "overworld", 1337L);
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class, created::get);
|
||||
assertSame(refusal, failure.getCause());
|
||||
@@ -165,14 +165,14 @@ public class BukkitWorldReconcilerRuntimeTest {
|
||||
when(dimension.getLoadKey()).thenReturn("overworld");
|
||||
when(engine.getData()).thenReturn(data);
|
||||
when(data.getDataFolder()).thenReturn(pack.toFile());
|
||||
return new RuntimeFixture(backend(mock(Iris.class)), world, key, generator, engine, history, root, pack);
|
||||
return new RuntimeFixture(backend(mock(IrisWorldGeneratorResolver.class)), world, key, generator, engine, history, root, pack);
|
||||
}
|
||||
|
||||
private static BukkitWorldReconciler.Backend backend(Iris plugin) throws Exception {
|
||||
private static BukkitWorldReconciler.Backend backend(IrisWorldGeneratorResolver resolver) throws Exception {
|
||||
Class<?> backendClass = Class.forName(BukkitWorldReconciler.class.getName() + "$BukkitBackend");
|
||||
Constructor<?> constructor = backendClass.getDeclaredConstructor(Iris.class);
|
||||
Constructor<?> constructor = backendClass.getDeclaredConstructor(IrisWorldGeneratorResolver.class);
|
||||
constructor.setAccessible(true);
|
||||
return (BukkitWorldReconciler.Backend) constructor.newInstance(plugin);
|
||||
return (BukkitWorldReconciler.Backend) constructor.newInstance(resolver);
|
||||
}
|
||||
|
||||
private record RuntimeFixture(BukkitWorldReconciler.Backend backend, World world, NamespacedKey key,
|
||||
|
||||
+21
-2
@@ -175,6 +175,19 @@ def generateNativeRuntime = tasks.register('generateNativeRuntime') {
|
||||
nativeRuntimeOutput.get().asFile, nativeRuntimeRules.get().asFile)
|
||||
}
|
||||
}
|
||||
// The Bukkit jar leaves VolmLib's noise natives out and pins them instead; NoiseNatives downloads the
|
||||
// platform's binary at startup and verifies it against this manifest.
|
||||
def noiseNativesOutput = layout.buildDirectory.dir('generated/noise-natives')
|
||||
def generateNoiseNatives = tasks.register('generateNoiseNatives') {
|
||||
inputs.files(included)
|
||||
outputs.dir(noiseNativesOutput)
|
||||
doLast {
|
||||
File manifest = new File(noiseNativesOutput.get().asFile, NoiseNativeArtifacts.MANIFEST)
|
||||
NoiseNativeArtifacts.generate(included.resolve(), localVolmLibCheckout, manifest).each { String warning ->
|
||||
logger.warn(warning)
|
||||
}
|
||||
}
|
||||
}
|
||||
def jarJar = configurations.create('jarJar')
|
||||
dependencies {
|
||||
add('included', project(path: ':core', configuration: 'shadow'))
|
||||
@@ -184,8 +197,9 @@ dependencies {
|
||||
|
||||
tasks.named('jar', Jar).configure {
|
||||
inputs.files(included)
|
||||
dependsOn(generateNativeRuntime)
|
||||
dependsOn(generateNativeRuntime, generateNoiseNatives)
|
||||
from(nativeRuntimeOutput)
|
||||
from(noiseNativesOutput)
|
||||
from(tasks.named('generateVolmLibStamp')) {
|
||||
into('META-INF/volmit')
|
||||
}
|
||||
@@ -196,6 +210,8 @@ tasks.named('jar', Jar).configure {
|
||||
exclude('META-INF/INDEX.LIST')
|
||||
exclude('languages/**')
|
||||
exclude('com/fren_gor/**')
|
||||
exclude(NoiseNativeArtifacts.RESOURCE_PREFIX + '**')
|
||||
exclude('iris-language-guides/*.txt')
|
||||
|
||||
}
|
||||
archiveFileName.set(bukkitArtifactName)
|
||||
@@ -510,6 +526,7 @@ List<String> requiredBukkitArtifactEntries = [
|
||||
'slimjar.dat',
|
||||
'slimjar-resolutions.dat',
|
||||
'META-INF/iris/native-runtime.properties',
|
||||
NoiseNativeArtifacts.MANIFEST,
|
||||
'META-INF/volmit/volmlib.properties',
|
||||
'iris-language-source.properties',
|
||||
'agent.jar',
|
||||
@@ -547,6 +564,7 @@ tasks.register('verifyBukkitArtifact') {
|
||||
16,
|
||||
runtimeDownloadedPrefixes)
|
||||
NativeRuntimeArtifacts.verify(archive, nativeRuntimeModules, embeddedNatives())
|
||||
NoiseNativeArtifacts.verify(archive)
|
||||
logger.lifecycle("Verified ${archive.name} packaging and class reference graph")
|
||||
}
|
||||
}
|
||||
@@ -735,7 +753,8 @@ pluginPackaging {
|
||||
policyName = 'Iris Bukkit'
|
||||
packed = true
|
||||
packedJarAccessors = ['art/arcane/iris/platform/bukkit/plugin/VolmitPlugin#getJarFile']
|
||||
packedPayloadOnlyPrefixes = ['iris-language-guides/']
|
||||
packedPayloadOnlyPrefixes = ['iris-language-guides/', 'META-INF/iris/generation-kernels/abi-', 'iris/icons/views/', 'iris/datapack/']
|
||||
packedMaximumBootstrapClasses = 90
|
||||
stripDirectories = true
|
||||
stripLocalVariables = true
|
||||
releaseCompression = providers.gradleProperty('compactRelease')
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import org.gradle.api.GradleException;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* Pins the VolmLib noise natives the Bukkit jar leaves out. The runtime downloads the binary for its platform and
|
||||
* accepts it only when the size and SHA-256 recorded here match; the git blob id lets it fetch the exact bytes by
|
||||
* content even when the build had no VolmLib checkout to name a commit.
|
||||
*/
|
||||
public final class NoiseNativeArtifacts {
|
||||
public static final String MANIFEST = "META-INF/iris/noise-natives.properties";
|
||||
public static final String RESOURCE_PREFIX = "art/arcane/volmlib/native/";
|
||||
public static final String SOURCE_PATH = "shared/native/noise/prebuilt";
|
||||
|
||||
private NoiseNativeArtifacts() {
|
||||
}
|
||||
|
||||
public static List<String> generate(Collection<File> jars, File volmLibDirectory, File output) throws IOException {
|
||||
Map<String, NativeFile> natives = collect(jars);
|
||||
if (natives.isEmpty()) {
|
||||
throw new GradleException("No VolmLib noise natives under " + RESOURCE_PREFIX + " in " + jars);
|
||||
}
|
||||
List<String> warnings = new ArrayList<>();
|
||||
String commit = volmLibDirectory == null ? "" : commit(volmLibDirectory, natives, warnings);
|
||||
Properties manifest = new Properties();
|
||||
manifest.setProperty("commit", commit);
|
||||
manifest.setProperty("source", SOURCE_PATH);
|
||||
manifest.setProperty("platforms", String.join(",", natives.keySet()));
|
||||
for (NativeFile file : natives.values()) {
|
||||
manifest.setProperty(file.platform() + ".file", file.name());
|
||||
manifest.setProperty(file.platform() + ".size", String.valueOf(file.size()));
|
||||
manifest.setProperty(file.platform() + ".sha256", file.sha256());
|
||||
manifest.setProperty(file.platform() + ".blob", file.blob());
|
||||
}
|
||||
Files.createDirectories(output.toPath().getParent());
|
||||
try (Writer writer = Files.newBufferedWriter(output.toPath(), StandardCharsets.UTF_8)) {
|
||||
manifest.store(writer, null);
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
public static void verify(File artifact) throws IOException {
|
||||
try (JarFile jar = new JarFile(artifact)) {
|
||||
if (jar.getJarEntry(MANIFEST) == null) {
|
||||
throw new GradleException(artifact.getName() + " is missing " + MANIFEST);
|
||||
}
|
||||
Enumeration<JarEntry> entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
String name = entries.nextElement().getName();
|
||||
if (name.startsWith(RESOURCE_PREFIX) && !name.endsWith("/")) {
|
||||
throw new GradleException(artifact.getName() + " bundles " + name
|
||||
+ "; the Bukkit jar downloads noise natives through " + MANIFEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String sha256(byte[] bytes) {
|
||||
return HexFormat.of().formatHex(digest("SHA-256", bytes));
|
||||
}
|
||||
|
||||
static String blob(byte[] bytes) {
|
||||
byte[] header = ("blob " + bytes.length + "\0").getBytes(StandardCharsets.US_ASCII);
|
||||
byte[] object = new byte[header.length + bytes.length];
|
||||
System.arraycopy(header, 0, object, 0, header.length);
|
||||
System.arraycopy(bytes, 0, object, header.length, bytes.length);
|
||||
return HexFormat.of().formatHex(digest("SHA-1", object));
|
||||
}
|
||||
|
||||
private static Map<String, NativeFile> collect(Collection<File> jars) throws IOException {
|
||||
Map<String, NativeFile> natives = new TreeMap<>();
|
||||
for (File file : jars) {
|
||||
if (!file.isFile()) {
|
||||
continue;
|
||||
}
|
||||
try (JarFile jar = new JarFile(file)) {
|
||||
Enumeration<JarEntry> entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
if (entry.isDirectory() || !name.startsWith(RESOURCE_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
String[] parts = name.substring(RESOURCE_PREFIX.length()).split("/");
|
||||
if (parts.length != 2) {
|
||||
continue;
|
||||
}
|
||||
byte[] bytes;
|
||||
try (InputStream input = jar.getInputStream(entry)) {
|
||||
bytes = input.readAllBytes();
|
||||
}
|
||||
NativeFile resolved = new NativeFile(parts[0], parts[1], bytes.length, sha256(bytes), blob(bytes));
|
||||
NativeFile previous = natives.putIfAbsent(parts[0], resolved);
|
||||
if (previous != null && !previous.equals(resolved)) {
|
||||
throw new GradleException("Conflicting noise natives for " + parts[0] + " in " + jars);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return natives;
|
||||
}
|
||||
|
||||
private static String commit(File checkout, Map<String, NativeFile> natives, List<String> warnings) {
|
||||
String commit = git(checkout, "log", "-1", "--format=%H", "--", SOURCE_PATH);
|
||||
if (commit == null || commit.isEmpty()) {
|
||||
warnings.add("Noise natives: no commit touches " + SOURCE_PATH + " in " + checkout + "; downloads fall back to the blob id");
|
||||
return "";
|
||||
}
|
||||
for (NativeFile file : natives.values()) {
|
||||
String path = commit + ":" + SOURCE_PATH + "/" + file.platform() + "/" + file.name();
|
||||
if (!file.blob().equals(git(checkout, "rev-parse", path))) {
|
||||
warnings.add("Noise natives: " + file.platform() + " differs from " + commit.substring(0, 7)
|
||||
+ " (uncommitted rebuild?); downloads fall back to the blob id");
|
||||
return "";
|
||||
}
|
||||
}
|
||||
String remotes = git(checkout, "branch", "-r", "--contains", commit);
|
||||
if (remotes == null || remotes.isEmpty()) {
|
||||
warnings.add("Noise natives: " + commit.substring(0, 7) + " is not on any remote branch; downloads fail until it is pushed");
|
||||
}
|
||||
return commit;
|
||||
}
|
||||
|
||||
private static String git(File directory, String... arguments) {
|
||||
List<String> command = new ArrayList<>(List.of("git", "-C", directory.getAbsolutePath()));
|
||||
command.addAll(List.of(arguments));
|
||||
try {
|
||||
Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) {
|
||||
return null;
|
||||
}
|
||||
return output;
|
||||
} catch (IOException failure) {
|
||||
return null;
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] digest(String algorithm, byte[] bytes) {
|
||||
try {
|
||||
return MessageDigest.getInstance(algorithm).digest(bytes);
|
||||
} catch (NoSuchAlgorithmException missing) {
|
||||
throw new IllegalStateException(missing);
|
||||
}
|
||||
}
|
||||
|
||||
private record NativeFile(String platform, String name, long size, String sha256, String blob) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import org.gradle.api.GradleException;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.TreeMap;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NoiseNativeArtifactsTest {
|
||||
private static final String LINUX = "art/arcane/volmlib/native/linux-x86_64/libvolmlib_noise.so";
|
||||
private static final String WINDOWS = "art/arcane/volmlib/native/windows-x86_64/volmlib_noise.dll";
|
||||
private static final byte[] LINUX_BYTES = "linux-native".getBytes(StandardCharsets.UTF_8);
|
||||
private static final byte[] WINDOWS_BYTES = "windows-native".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@Rule
|
||||
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void blobMatchesGitHashObject() throws Exception {
|
||||
File file = temporaryFolder.newFile("blob.bin");
|
||||
Files.write(file.toPath(), LINUX_BYTES);
|
||||
assertEquals(git(temporaryFolder.getRoot(), "hash-object", file.getAbsolutePath()), NoiseNativeArtifacts.blob(LINUX_BYTES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateRecordsEveryPlatformWithoutCommitWhenNoCheckoutIsKnown() throws Exception {
|
||||
File output = temporaryFolder.getRoot().toPath().resolve("out/noise-natives.properties").toFile();
|
||||
List<String> warnings = NoiseNativeArtifacts.generate(List.of(volmLibJar()), null, output);
|
||||
|
||||
Properties manifest = read(output);
|
||||
assertEquals("", manifest.getProperty("commit"));
|
||||
assertEquals("linux-x86_64,windows-x86_64", manifest.getProperty("platforms"));
|
||||
assertEquals("libvolmlib_noise.so", manifest.getProperty("linux-x86_64.file"));
|
||||
assertEquals(String.valueOf(LINUX_BYTES.length), manifest.getProperty("linux-x86_64.size"));
|
||||
assertEquals(NoiseNativeArtifacts.sha256(LINUX_BYTES), manifest.getProperty("linux-x86_64.sha256"));
|
||||
assertEquals(NoiseNativeArtifacts.blob(WINDOWS_BYTES), manifest.getProperty("windows-x86_64.blob"));
|
||||
assertTrue(warnings.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatePinsTheLastCommitThatHoldsTheSameBytes() throws Exception {
|
||||
File checkout = checkout(LINUX_BYTES, WINDOWS_BYTES);
|
||||
File output = temporaryFolder.newFile("pinned.properties");
|
||||
NoiseNativeArtifacts.generate(List.of(volmLibJar()), checkout, output);
|
||||
|
||||
assertEquals(git(checkout, "rev-parse", "HEAD"), read(output).getProperty("commit"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateDropsTheCommitWhenTheCheckoutBytesDiffer() throws Exception {
|
||||
File checkout = checkout("stale".getBytes(StandardCharsets.UTF_8), WINDOWS_BYTES);
|
||||
File output = temporaryFolder.newFile("stale.properties");
|
||||
List<String> warnings = NoiseNativeArtifacts.generate(List.of(volmLibJar()), checkout, output);
|
||||
|
||||
assertEquals("", read(output).getProperty("commit"));
|
||||
assertFalse(warnings.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateRejectsJarsWithoutNatives() throws Exception {
|
||||
File empty = jar("empty.jar", Map.of("plugin.yml", new byte[]{1}));
|
||||
File output = temporaryFolder.newFile("none.properties");
|
||||
assertThrows(GradleException.class, () -> NoiseNativeArtifacts.generate(List.of(empty), null, output));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void verifyRejectsBundledNativesAndMissingManifest() throws Exception {
|
||||
File manifest = temporaryFolder.newFile("manifest.properties");
|
||||
NoiseNativeArtifacts.generate(List.of(volmLibJar()), null, manifest);
|
||||
byte[] manifestBytes = Files.readAllBytes(manifest.toPath());
|
||||
|
||||
NoiseNativeArtifacts.verify(jar("clean.jar", Map.of(NoiseNativeArtifacts.MANIFEST, manifestBytes)));
|
||||
assertThrows(GradleException.class, () -> NoiseNativeArtifacts.verify(
|
||||
jar("bundled.jar", Map.of(NoiseNativeArtifacts.MANIFEST, manifestBytes, LINUX, LINUX_BYTES))));
|
||||
assertThrows(GradleException.class, () -> NoiseNativeArtifacts.verify(
|
||||
jar("unpinned.jar", Map.of("plugin.yml", new byte[]{1}))));
|
||||
}
|
||||
|
||||
private File volmLibJar() throws IOException {
|
||||
return jar("volmlib-shared.jar", Map.of(LINUX, LINUX_BYTES, WINDOWS, WINDOWS_BYTES,
|
||||
"art/arcane/volmlib/util/Noise.class", new byte[]{(byte) 0xCA, (byte) 0xFE}));
|
||||
}
|
||||
|
||||
private File checkout(byte[] linux, byte[] windows) throws Exception {
|
||||
File root = temporaryFolder.newFolder();
|
||||
Path prebuilt = root.toPath().resolve(NoiseNativeArtifacts.SOURCE_PATH);
|
||||
Files.createDirectories(prebuilt.resolve("linux-x86_64"));
|
||||
Files.createDirectories(prebuilt.resolve("windows-x86_64"));
|
||||
Files.write(prebuilt.resolve("linux-x86_64/libvolmlib_noise.so"), linux);
|
||||
Files.write(prebuilt.resolve("windows-x86_64/volmlib_noise.dll"), windows);
|
||||
git(root, "init", "-q");
|
||||
git(root, "add", ".");
|
||||
git(root, "-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-q", "-m", "natives");
|
||||
return root;
|
||||
}
|
||||
|
||||
private File jar(String name, Map<String, byte[]> entries) throws IOException {
|
||||
File file = new File(temporaryFolder.getRoot(), name);
|
||||
try (JarOutputStream output = new JarOutputStream(new FileOutputStream(file))) {
|
||||
for (Map.Entry<String, byte[]> entry : new TreeMap<>(entries).entrySet()) {
|
||||
output.putNextEntry(new JarEntry(entry.getKey()));
|
||||
output.write(entry.getValue());
|
||||
output.closeEntry();
|
||||
}
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static Properties read(File file) throws IOException {
|
||||
Properties properties = new Properties();
|
||||
try (Reader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
|
||||
properties.load(reader);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
private static String git(File directory, String... arguments) throws Exception {
|
||||
List<String> command = new ArrayList<>(List.of("git", "-C", directory.getAbsolutePath()));
|
||||
command.addAll(List.of(arguments));
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim();
|
||||
assertEquals(output, 0, process.waitFor());
|
||||
return output;
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -62,13 +62,20 @@ def languageGuidesTask = tasks.register('generateLanguageGuides') {
|
||||
doLast {
|
||||
File output = guideDirectory.get().asFile
|
||||
output.mkdirs()
|
||||
// index.properties lets jars that leave the guide text out accept an upstream guide only when it is
|
||||
// byte-identical to the one this build would have bundled.
|
||||
Properties index = new Properties()
|
||||
for (File source : languageSourceFiles) {
|
||||
List<String> header = source.readLines('UTF-8').takeWhile { String line ->
|
||||
line.isBlank() || line.stripLeading().startsWith('#')
|
||||
}
|
||||
String locale = source.name.substring(0, source.name.length() - '.toml'.length())
|
||||
new File(output, locale + '.txt').setText(header.join('\n').stripTrailing() + '\n', 'UTF-8')
|
||||
String guide = header.join('\n').stripTrailing() + '\n'
|
||||
new File(output, locale + '.txt').setText(guide, 'UTF-8')
|
||||
index.setProperty(locale, java.security.MessageDigest.getInstance('SHA-256')
|
||||
.digest(guide.getBytes('UTF-8')).encodeHex().toString())
|
||||
}
|
||||
new File(output, 'index.properties').withWriter('UTF-8') { Writer writer -> index.store(writer, null) }
|
||||
}
|
||||
}
|
||||
tasks.named('processResources').configure {
|
||||
|
||||
@@ -88,6 +88,7 @@ public final class IrisLanguage {
|
||||
new CopyOnWriteArrayList<>();
|
||||
private static volatile File dataFolder;
|
||||
private static volatile String activeLocale = CATALOG.englishLocale();
|
||||
private static final Set<String> GUIDE_FETCHES = ConcurrentHashMap.newKeySet();
|
||||
private static volatile RemoteLanguageCatalog remote;
|
||||
private static volatile Path remoteRoot;
|
||||
private static volatile PluginLanguageService selections;
|
||||
@@ -668,13 +669,51 @@ public final class IrisLanguage {
|
||||
|
||||
private static void refreshLanguageGuide(File file, String locale) {
|
||||
try {
|
||||
IrisLanguageGuide.refresh(file, locale);
|
||||
ClassLoader resources = IrisLanguage.class.getClassLoader();
|
||||
if (!IrisLanguageGuide.refresh(file, locale, resources) && IrisLanguageGuide.fetchable(locale, resources)) {
|
||||
fetchLanguageGuide(file, locale, resources);
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
IrisLogging.error("Could not update the language guide in " + file.getPath() + ".");
|
||||
IrisLogging.reportError(failure);
|
||||
}
|
||||
}
|
||||
|
||||
// Jars that leave the guides out (the size-capped Bukkit jar) take this build's guide from the upstream
|
||||
// locale file, once per locale per run; it is cached only when its digest matches the build's guide index.
|
||||
private static void fetchLanguageGuide(File file, String locale, ClassLoader resources) {
|
||||
File root = dataFolder;
|
||||
if (root == null || !GUIDE_FETCHES.add(locale)) {
|
||||
return;
|
||||
}
|
||||
Path cache = IrisLanguageGuide.guideCache(file);
|
||||
Path source = cache.resolve(locale + ".source.toml");
|
||||
try {
|
||||
Files.deleteIfExists(source);
|
||||
} catch (IOException failure) {
|
||||
IrisLogging.debug("Language guide source " + source + " could not be cleared: " + failure.getMessage());
|
||||
return;
|
||||
}
|
||||
remote(root).requestInstallIfMissing(locale, source, IrisLanguage::validateDownload, result -> {
|
||||
try {
|
||||
if (result.successful()
|
||||
&& IrisLanguageGuide.cacheUpstream(cache, locale, Files.readString(source, StandardCharsets.UTF_8), resources)) {
|
||||
IrisLanguageGuide.refresh(file, locale, resources);
|
||||
} else {
|
||||
IrisLogging.debug("Language guide for " + locale + " is not available upstream for this build");
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
IrisLogging.debug("Language guide for " + locale + " could not be cached: " + failure.getMessage());
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(source);
|
||||
} catch (IOException ignored) {
|
||||
IrisLogging.debug("Language guide source " + source + " could not be removed");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void createEnglishLanguageIfMissing(File root) throws IOException {
|
||||
Path target = overrideFile(Objects.requireNonNull(root, "Language data folder"), CATALOG.englishLocale()).toPath();
|
||||
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||
|
||||
@@ -7,20 +7,28 @@ import art.arcane.volmlib.util.localization.TomlLanguageWriter;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
final class IrisLanguageGuide {
|
||||
private static final String START = "# === Iris language guide ===";
|
||||
private static final String END = "# === End Iris language guide ===";
|
||||
private static final String ENGLISH_LOCALE = "en_US";
|
||||
private static final String GUIDE_DIRECTORY = "iris-language-guides/";
|
||||
private static final String GUIDE_INDEX = "index.properties";
|
||||
private static final String GUIDE_CACHE = ".guides";
|
||||
private static final Pattern UNDESCRIBED_VARIABLES = Pattern.compile("#\\s+(?:\\{[A-Za-z][A-Za-z0-9_]*}\\s*)+");
|
||||
private static final Map<String, String> UNMARKED_GUIDE_FINGERPRINTS = Map.ofEntries(
|
||||
Map.entry("de_DE", "c32159c55e437c3e0e638a48618d2c4ea3bcefebacd3883e94095c986fb9a7e6"),
|
||||
@@ -318,12 +326,91 @@ final class IrisLanguageGuide {
|
||||
}
|
||||
|
||||
static String header(String locale) throws IOException {
|
||||
try (InputStream input = IrisLanguageGuide.class.getResourceAsStream("/iris-language-guides/" + locale + ".txt")) {
|
||||
return header(locale, null, IrisLanguageGuide.class.getClassLoader());
|
||||
}
|
||||
|
||||
/**
|
||||
* The guide this build ships for {@code locale}: the bundled copy, the English template, or a copy cached from
|
||||
* the upstream locale file whose digest matches the build's guide index. Null when none is available yet, so
|
||||
* a translated guide is never replaced with English or with a different revision's text.
|
||||
*/
|
||||
static String header(String locale, Path guideCache, ClassLoader resources) throws IOException {
|
||||
try (InputStream input = resources.getResourceAsStream(GUIDE_DIRECTORY + locale + ".txt")) {
|
||||
if (input != null) {
|
||||
return new String(input.readAllBytes(), StandardCharsets.UTF_8).stripTrailing() + "\n";
|
||||
}
|
||||
}
|
||||
return englishHeader(locale);
|
||||
if (ENGLISH_LOCALE.equals(locale)) {
|
||||
return englishHeader(locale);
|
||||
}
|
||||
String expected = expectedDigest(locale, resources);
|
||||
if (expected == null || guideCache == null) {
|
||||
return null;
|
||||
}
|
||||
Path cached = guideCache.resolve(expected + ".txt");
|
||||
if (!Files.isRegularFile(cached, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return null;
|
||||
}
|
||||
String text = Files.readString(cached, StandardCharsets.UTF_8);
|
||||
return expected.equals(sha256(text)) ? text : null;
|
||||
}
|
||||
|
||||
static Path guideCache(File languageFile) {
|
||||
return languageFile.toPath().toAbsolutePath().resolveSibling(GUIDE_CACHE);
|
||||
}
|
||||
|
||||
static boolean fetchable(String locale, ClassLoader resources) throws IOException {
|
||||
return !ENGLISH_LOCALE.equals(locale) && expectedDigest(locale, resources) != null;
|
||||
}
|
||||
|
||||
/** Stores the guide from an upstream locale file when it is exactly the guide this build expects. */
|
||||
static boolean cacheUpstream(Path guideCache, String locale, String upstream, ClassLoader resources) throws IOException {
|
||||
String expected = expectedDigest(locale, resources);
|
||||
String guide = extractHeader(upstream);
|
||||
if (expected == null || !expected.equals(sha256(guide))) {
|
||||
return false;
|
||||
}
|
||||
Files.createDirectories(guideCache);
|
||||
Path temporary = Files.createTempFile(guideCache, locale + "-", ".tmp");
|
||||
try {
|
||||
Files.writeString(temporary, guide, StandardCharsets.UTF_8);
|
||||
Files.move(temporary, guideCache.resolve(expected + ".txt"), StandardCopyOption.REPLACE_EXISTING,
|
||||
StandardCopyOption.ATOMIC_MOVE);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Same rule as core/build.gradle generateLanguageGuides: the leading blank and comment lines. */
|
||||
static String extractHeader(String toml) {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (String line : toml.split("\\R", -1)) {
|
||||
if (!line.isBlank() && !line.stripLeading().startsWith("#")) {
|
||||
break;
|
||||
}
|
||||
lines.add(line);
|
||||
}
|
||||
return String.join("\n", lines).stripTrailing() + "\n";
|
||||
}
|
||||
|
||||
private static String expectedDigest(String locale, ClassLoader resources) throws IOException {
|
||||
try (InputStream input = resources.getResourceAsStream(GUIDE_DIRECTORY + GUIDE_INDEX)) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
Properties index = new Properties();
|
||||
index.load(new InputStreamReader(input, StandardCharsets.UTF_8));
|
||||
return index.getProperty(locale);
|
||||
}
|
||||
}
|
||||
|
||||
private static String sha256(String text) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException missing) {
|
||||
throw new IllegalStateException(missing);
|
||||
}
|
||||
}
|
||||
|
||||
static String englishHeader(String locale) {
|
||||
@@ -339,14 +426,23 @@ final class IrisLanguageGuide {
|
||||
}
|
||||
|
||||
static void refresh(File file, String locale) throws IOException {
|
||||
refresh(file, locale, IrisLanguageGuide.class.getClassLoader());
|
||||
}
|
||||
|
||||
/** Returns false when this build's guide for the locale is not available yet. */
|
||||
static boolean refresh(File file, String locale, ClassLoader resources) throws IOException {
|
||||
if (!Files.isRegularFile(file.toPath(), LinkOption.NOFOLLOW_LINKS)
|
||||
|| Files.size(file.toPath()) > 2L * 1024L * 1024L) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
String guide = header(locale, guideCache(file), resources);
|
||||
if (guide == null) {
|
||||
return false;
|
||||
}
|
||||
String original = Files.readString(file.toPath(), StandardCharsets.UTF_8);
|
||||
String updated = replaceHeader(original, header(locale), locale);
|
||||
String updated = replaceHeader(original, guide, locale);
|
||||
if (original.equals(updated)) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
LanguageFileEditor.update(file.toPath(), current -> {
|
||||
if (!current.equals(original)) {
|
||||
@@ -354,6 +450,7 @@ final class IrisLanguageGuide {
|
||||
}
|
||||
return new LanguageFileEditor.Prepared<>(updated, null);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
static String replaceHeader(String content, String header, String locale) {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package art.arcane.iris.platform.bootstrap;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Provides VolmLib's native noise kernels to jars that leave them out (the size-capped Bukkit jar). The build pins
|
||||
* each platform's binary in {@link #MANIFEST}; the matching file is downloaded once into a cache folder named by its
|
||||
* SHA-256 and handed to VolmLib through {@code volmlib.native.library}. Jars that bundle the kernels never download.
|
||||
* Any failure leaves VolmLib on its Java kernels, which produce identical output.
|
||||
*/
|
||||
public final class NoiseNatives {
|
||||
static final String MANIFEST = "META-INF/iris/noise-natives.properties";
|
||||
static final String LIBRARY_PROPERTY = "volmlib.native.library";
|
||||
static final String POLICY_PROPERTY = "volmlib.native";
|
||||
private static final String RESOURCE_PREFIX = "art/arcane/volmlib/native/";
|
||||
private static final String RAW_ROOT = "https://raw.githubusercontent.com/VolmitSoftware/VolmLib/";
|
||||
private static final String BLOB_ROOT = "https://api.github.com/repos/VolmitSoftware/VolmLib/git/blobs/";
|
||||
private static final int CONNECT_TIMEOUT_MILLIS = 5_000;
|
||||
private static final int READ_TIMEOUT_MILLIS = 15_000;
|
||||
|
||||
private NoiseNatives() {
|
||||
}
|
||||
|
||||
public static void provision(Path cacheRoot, SlimJar.BootstrapLogger logger) {
|
||||
if (System.getProperty(LIBRARY_PROPERTY) != null
|
||||
|| "off".equalsIgnoreCase(System.getProperty(POLICY_PROPERTY, "").trim())) {
|
||||
return;
|
||||
}
|
||||
String platform = platform(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
|
||||
Path library = install(cacheRoot, platform, NoiseNatives.class.getClassLoader(), NoiseNatives::download, logger);
|
||||
if (library != null) {
|
||||
System.setProperty(LIBRARY_PROPERTY, library.toAbsolutePath().toString());
|
||||
}
|
||||
}
|
||||
|
||||
static String platform(String operatingSystem, String architecture) {
|
||||
String os = operatingSystem.toLowerCase(Locale.ROOT);
|
||||
String family = os.contains("mac") ? "macos" : os.contains("linux") ? "linux" : os.contains("win") ? "windows" : null;
|
||||
String arch = switch (architecture) {
|
||||
case "aarch64", "arm64" -> "aarch64";
|
||||
case "amd64", "x86_64" -> "x86_64";
|
||||
default -> null;
|
||||
};
|
||||
return family == null || arch == null ? null : family + "-" + arch;
|
||||
}
|
||||
|
||||
static Path install(Path cacheRoot, String platform, ClassLoader resources, Fetcher fetcher,
|
||||
SlimJar.BootstrapLogger logger) {
|
||||
if (platform == null) {
|
||||
return null;
|
||||
}
|
||||
Pin pin = pin(resources, platform);
|
||||
if (pin == null || resources.getResource(RESOURCE_PREFIX + platform + "/" + pin.file()) != null) {
|
||||
return null;
|
||||
}
|
||||
Path target = cacheRoot.resolve(pin.sha256()).resolve(pin.file());
|
||||
try {
|
||||
if (Files.isRegularFile(target)) {
|
||||
if (pin.matches(Files.readAllBytes(target))) {
|
||||
return target;
|
||||
}
|
||||
Files.delete(target);
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
logger.error("Native noise cache " + target + " is unreadable (" + failure.getMessage() + ")");
|
||||
}
|
||||
List<String> failures = new ArrayList<>();
|
||||
for (URI source : pin.sources(platform)) {
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
byte[] bytes = fetcher.fetch(source, pin.size());
|
||||
if (!pin.matches(bytes)) {
|
||||
failures.add(source.getHost() + ": checksum mismatch");
|
||||
continue;
|
||||
}
|
||||
write(target, bytes);
|
||||
logger.info("Native noise kernels for " + platform + ": " + (bytes.length / 1024) + " KiB in "
|
||||
+ ((System.nanoTime() - started) / 1_000_000L) + " ms from " + source.getHost());
|
||||
return target;
|
||||
} catch (IOException failure) {
|
||||
failures.add(source.getHost() + ": " + failure.getMessage());
|
||||
}
|
||||
}
|
||||
logger.error("Native noise kernels unavailable for " + platform + " (" + String.join("; ", failures)
|
||||
+ "); generation uses the Java kernels with identical output. To install manually, save "
|
||||
+ pin.sources(platform).get(0) + " (sha256 " + pin.sha256() + ") as " + target);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Pin pin(ClassLoader resources, String platform) {
|
||||
Properties manifest = new Properties();
|
||||
try (InputStream input = resources.getResourceAsStream(MANIFEST)) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
try (Reader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) {
|
||||
manifest.load(reader);
|
||||
}
|
||||
} catch (IOException failure) {
|
||||
return null;
|
||||
}
|
||||
String file = manifest.getProperty(platform + ".file");
|
||||
String sha256 = manifest.getProperty(platform + ".sha256");
|
||||
String blob = manifest.getProperty(platform + ".blob");
|
||||
String size = manifest.getProperty(platform + ".size");
|
||||
if (file == null || sha256 == null || blob == null || size == null) {
|
||||
return null;
|
||||
}
|
||||
return new Pin(file, Long.parseLong(size), sha256, blob, manifest.getProperty("commit", ""),
|
||||
manifest.getProperty("source", ""));
|
||||
}
|
||||
|
||||
private static void write(Path target, byte[] bytes) throws IOException {
|
||||
Files.createDirectories(target.getParent());
|
||||
Path temporary = Files.createTempFile(target.getParent(), target.getFileName().toString(), ".part");
|
||||
try {
|
||||
Files.write(temporary, bytes);
|
||||
try {
|
||||
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException unsupported) {
|
||||
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] download(URI source, long size) throws IOException {
|
||||
URL url = source.toURL();
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS);
|
||||
connection.setReadTimeout(READ_TIMEOUT_MILLIS);
|
||||
connection.setRequestProperty("User-Agent", "Iris");
|
||||
connection.setRequestProperty("Accept", "application/vnd.github.raw+json");
|
||||
try {
|
||||
int status = connection.getResponseCode();
|
||||
if (status != HttpURLConnection.HTTP_OK) {
|
||||
throw new IOException("HTTP " + status);
|
||||
}
|
||||
try (InputStream input = connection.getInputStream()) {
|
||||
byte[] bytes = input.readNBytes((int) Math.min(Integer.MAX_VALUE - 8L, size + 1L));
|
||||
if (bytes.length != size) {
|
||||
throw new IOException("expected " + size + " bytes, got " + bytes.length);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface Fetcher {
|
||||
byte[] fetch(URI source, long size) throws IOException;
|
||||
}
|
||||
|
||||
private record Pin(String file, long size, String sha256, String blob, String commit, String source) {
|
||||
boolean matches(byte[] bytes) {
|
||||
if (bytes.length != size) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)).equals(sha256);
|
||||
} catch (NoSuchAlgorithmException missing) {
|
||||
throw new IllegalStateException(missing);
|
||||
}
|
||||
}
|
||||
|
||||
List<URI> sources(String platform) {
|
||||
List<URI> sources = new ArrayList<>(2);
|
||||
if (!commit.isEmpty() && !source.isEmpty()) {
|
||||
sources.add(URI.create(RAW_ROOT + commit + "/" + source + "/" + platform + "/" + file));
|
||||
}
|
||||
sources.add(URI.create(BLOB_ROOT + blob));
|
||||
return sources;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ public class SlimJar {
|
||||
})
|
||||
.build();
|
||||
nativeProviders = libraries.openProviderLoader(downloadPath);
|
||||
NoiseNatives.provision(downloadPath.resolveSibling("natives"), logger);
|
||||
loaded.set(true);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
@@ -100,6 +101,22 @@ public class SlimJar {
|
||||
})
|
||||
.build();
|
||||
nativeProviders = libraries.openProviderLoader(downloadPath);
|
||||
NoiseNatives.provision(downloadPath.resolveSibling("natives"), new BootstrapLogger() {
|
||||
@Override
|
||||
public void info(String message) {
|
||||
plugin.getLogger().info(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
plugin.getLogger().warning(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String message) {
|
||||
SlimJar.debug(plugin, message);
|
||||
}
|
||||
});
|
||||
loaded.set(true);
|
||||
debug(plugin, "Libraries loaded successfully!");
|
||||
} finally {
|
||||
|
||||
@@ -19,8 +19,6 @@
|
||||
package art.arcane.iris.platform.bukkit.plugin;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
@@ -31,11 +29,14 @@ import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@SuppressWarnings("EmptyMethod")
|
||||
public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
public static final boolean bad = false;
|
||||
private final KList<Runnable> postShutdown = new KList<>();
|
||||
private final List<Runnable> postShutdown = new ArrayList<>();
|
||||
|
||||
public File getJarFile() {
|
||||
return getFile();
|
||||
@@ -45,7 +46,7 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
postShutdown.add(r);
|
||||
}
|
||||
|
||||
protected void runPostShutdown() {
|
||||
public void runPostShutdown() {
|
||||
postShutdown.forEach(Runnable::run);
|
||||
}
|
||||
|
||||
@@ -77,8 +78,6 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
|
||||
private void outputInfo() {
|
||||
try {
|
||||
IO.delete(getDataFolder("info"));
|
||||
getDataFolder("info").mkdirs();
|
||||
outputPluginInfo();
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
@@ -126,15 +125,13 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
|
||||
public File getDataFile(String... strings) {
|
||||
File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator));
|
||||
File f = new File(getDataFolder(), String.join(File.separator, strings));
|
||||
f.getParentFile().mkdirs();
|
||||
return f;
|
||||
}
|
||||
|
||||
public File getDataFileList(String pre, String[] strings) {
|
||||
KList<String> v = new KList<>(strings);
|
||||
v.add(0, pre);
|
||||
File f = new File(getDataFolder(), v.toString(File.separator));
|
||||
File f = new File(getDataFolder(), String.join(File.separator, prefixed(pre, strings)));
|
||||
f.getParentFile().mkdirs();
|
||||
return f;
|
||||
}
|
||||
@@ -144,7 +141,7 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
return super.getDataFolder();
|
||||
}
|
||||
|
||||
File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator));
|
||||
File f = new File(getDataFolder(), String.join(File.separator, strings));
|
||||
f.mkdirs();
|
||||
|
||||
return f;
|
||||
@@ -155,23 +152,25 @@ public abstract class VolmitPlugin extends JavaPlugin implements Listener {
|
||||
return super.getDataFolder();
|
||||
}
|
||||
|
||||
File f = new File(getDataFolder(), new KList<>(strings).toString(File.separator));
|
||||
File f = new File(getDataFolder(), String.join(File.separator, strings));
|
||||
|
||||
return f;
|
||||
}
|
||||
|
||||
public File getDataFolderList(String pre, String[] strings) {
|
||||
KList<String> v = new KList<>(strings);
|
||||
v.add(0, pre);
|
||||
if (v.size() == 0) {
|
||||
return super.getDataFolder();
|
||||
}
|
||||
File f = new File(getDataFolder(), v.toString(File.separator));
|
||||
File f = new File(getDataFolder(), String.join(File.separator, prefixed(pre, strings)));
|
||||
f.mkdirs();
|
||||
|
||||
return f;
|
||||
}
|
||||
|
||||
private static List<String> prefixed(String pre, String[] strings) {
|
||||
List<String> path = new ArrayList<>(strings.length + 1);
|
||||
path.add(pre);
|
||||
path.addAll(Arrays.asList(strings));
|
||||
return path;
|
||||
}
|
||||
|
||||
public abstract void start();
|
||||
|
||||
public abstract void stop();
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package art.arcane.iris.localization;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class IrisLanguageGuideCacheTest {
|
||||
private static final String LOCALE = "de_DE";
|
||||
private static final String GUIDE = "# === Iris language guide ===\n# Deutsche Anleitung\n# === End Iris language guide ===\n";
|
||||
private static final String BODY = "\n[iris.command]\nunknown = 'Unbekannt'\n";
|
||||
|
||||
@Rule
|
||||
public final TemporaryFolder temporary = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void unbundledGuideComesFromAnUpstreamCopyOnlyWhenItMatchesTheBuildIndex() throws Exception {
|
||||
Path cache = temporary.newFolder(".guides").toPath();
|
||||
try (URLClassLoader resources = indexOnly(GUIDE)) {
|
||||
assertNull(IrisLanguageGuide.header(LOCALE, cache, resources));
|
||||
assertFalse(IrisLanguageGuide.cacheUpstream(cache, LOCALE, GUIDE.replace("Deutsche", "Alte") + BODY, resources));
|
||||
assertNull(IrisLanguageGuide.header(LOCALE, cache, resources));
|
||||
assertTrue(IrisLanguageGuide.cacheUpstream(cache, LOCALE, GUIDE.replace("\n", "\r\n") + BODY, resources));
|
||||
assertEquals(GUIDE, IrisLanguageGuide.header(LOCALE, cache, resources));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refreshLeavesATranslatedGuideAloneWhenThisBuildsGuideIsUnavailable() throws Exception {
|
||||
File languages = temporary.newFolder("languages");
|
||||
File file = new File(languages, LOCALE + ".toml");
|
||||
String original = "# === Iris language guide ===\n# Eigene Anleitung\n# === End Iris language guide ===\n" + BODY;
|
||||
Files.writeString(file.toPath(), original, StandardCharsets.UTF_8);
|
||||
try (URLClassLoader resources = indexOnly(GUIDE)) {
|
||||
assertFalse(IrisLanguageGuide.refresh(file, LOCALE, resources));
|
||||
assertTrue(IrisLanguageGuide.fetchable(LOCALE, resources));
|
||||
assertEquals(original, Files.readString(file.toPath(), StandardCharsets.UTF_8));
|
||||
|
||||
assertTrue(IrisLanguageGuide.cacheUpstream(IrisLanguageGuide.guideCache(file), LOCALE, GUIDE + BODY, resources));
|
||||
assertTrue(IrisLanguageGuide.refresh(file, LOCALE, resources));
|
||||
assertEquals(GUIDE + BODY, Files.readString(file.toPath(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void englishNeverNeedsADownload() throws Exception {
|
||||
try (URLClassLoader resources = new URLClassLoader(new URL[0], null)) {
|
||||
assertEquals(IrisLanguageGuide.englishHeader("en_US"), IrisLanguageGuide.header("en_US", null, resources));
|
||||
assertFalse(IrisLanguageGuide.fetchable("en_US", resources));
|
||||
assertFalse(IrisLanguageGuide.fetchable(LOCALE, resources));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extractedHeaderFollowsTheBuildRule() {
|
||||
assertEquals(GUIDE, IrisLanguageGuide.extractHeader("\n" + GUIDE + " \n[iris]\nkey = 'value'\n# trailing\n").stripLeading());
|
||||
assertEquals("\n", IrisLanguageGuide.extractHeader("[iris]\nkey = 'value'\n"));
|
||||
}
|
||||
|
||||
private URLClassLoader indexOnly(String guide) throws IOException {
|
||||
Path root = temporary.newFolder().toPath();
|
||||
Path index = root.resolve("iris-language-guides/index.properties");
|
||||
Files.createDirectories(index.getParent());
|
||||
Files.writeString(index, LOCALE + "=" + sha256(guide) + "\n", StandardCharsets.UTF_8);
|
||||
return new URLClassLoader(new URL[]{root.toUri().toURL()}, null);
|
||||
}
|
||||
|
||||
private static String sha256(String text) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package art.arcane.iris.platform.bootstrap;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NoiseNativesTest {
|
||||
private static final String PLATFORM = "linux-x86_64";
|
||||
private static final String FILE = "libvolmlib_noise.so";
|
||||
private static final byte[] NATIVE = "native-kernels".getBytes(StandardCharsets.UTF_8);
|
||||
private static final String COMMIT = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
@Rule
|
||||
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
private final List<String> errors = new ArrayList<>();
|
||||
private final SlimJar.BootstrapLogger logger = new SlimJar.BootstrapLogger() {
|
||||
@Override
|
||||
public void info(String message) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
errors.add(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String message) {
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
public void platformMatchesVolmLibNaming() {
|
||||
assertEquals("macos-aarch64", NoiseNatives.platform("Mac OS X", "aarch64"));
|
||||
assertEquals("windows-x86_64", NoiseNatives.platform("Windows 11", "amd64"));
|
||||
assertEquals("linux-aarch64", NoiseNatives.platform("Linux", "arm64"));
|
||||
assertNull(NoiseNatives.platform("FreeBSD", "amd64"));
|
||||
assertNull(NoiseNatives.platform("Linux", "riscv64"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void installsAVerifiedDownloadIntoAHashedCacheAndReusesIt() throws Exception {
|
||||
List<URI> requested = new ArrayList<>();
|
||||
Path cache = temporaryFolder.newFolder("cache").toPath();
|
||||
try (URLClassLoader resources = resources(manifest(""), Map.of())) {
|
||||
Path installed = NoiseNatives.install(cache, PLATFORM, resources, serving(requested, Map.of()), logger);
|
||||
assertEquals(cache.resolve(sha256(NATIVE)).resolve(FILE), installed);
|
||||
assertArrayEquals(NATIVE, Files.readAllBytes(installed));
|
||||
assertEquals(List.of(URI.create("https://api.github.com/repos/VolmitSoftware/VolmLib/git/blobs/" + blob(NATIVE))), requested);
|
||||
|
||||
Path reused = NoiseNatives.install(cache, PLATFORM, resources, (uri, limit) -> {
|
||||
throw new IOException("must not fetch");
|
||||
}, logger);
|
||||
assertEquals(installed, reused);
|
||||
}
|
||||
assertTrue(errors.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsBytesThatDoNotMatchThePinAndTriesTheNextSource() throws Exception {
|
||||
Path cache = temporaryFolder.newFolder("cache").toPath();
|
||||
URI raw = URI.create("https://raw.githubusercontent.com/VolmitSoftware/VolmLib/" + COMMIT
|
||||
+ "/shared/native/noise/prebuilt/" + PLATFORM + "/" + FILE);
|
||||
List<URI> requested = new ArrayList<>();
|
||||
try (URLClassLoader resources = resources(manifest(COMMIT), Map.of())) {
|
||||
Path installed = NoiseNatives.install(cache, PLATFORM, resources,
|
||||
serving(requested, Map.of(raw, "tampered!!!!!!".getBytes(StandardCharsets.UTF_8))), logger);
|
||||
assertArrayEquals(NATIVE, Files.readAllBytes(installed));
|
||||
assertEquals(raw, requested.get(0));
|
||||
assertEquals(2, requested.size());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fallsBackToJavaWithOneErrorWhenEverySourceFails() throws Exception {
|
||||
Path cache = temporaryFolder.newFolder("cache").toPath();
|
||||
try (URLClassLoader resources = resources(manifest(COMMIT), Map.of())) {
|
||||
assertNull(NoiseNatives.install(cache, PLATFORM, resources, (uri, limit) -> {
|
||||
throw new IOException("offline");
|
||||
}, logger));
|
||||
}
|
||||
assertEquals(1, errors.size());
|
||||
assertTrue(errors.get(0).contains(sha256(NATIVE)));
|
||||
try (Stream<Path> files = Files.walk(cache)) {
|
||||
assertFalse(files.anyMatch(Files::isRegularFile));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bundledNativesAndMissingManifestsNeverDownload() throws Exception {
|
||||
Path cache = temporaryFolder.newFolder("cache").toPath();
|
||||
NoiseNatives.Fetcher refuse = (uri, limit) -> {
|
||||
throw new AssertionError("must not fetch " + uri);
|
||||
};
|
||||
try (URLClassLoader bundled = resources(manifest(""), Map.of("art/arcane/volmlib/native/" + PLATFORM + "/" + FILE, NATIVE));
|
||||
URLClassLoader unpinned = resources(null, Map.of())) {
|
||||
assertNull(NoiseNatives.install(cache, PLATFORM, bundled, refuse, logger));
|
||||
assertNull(NoiseNatives.install(cache, PLATFORM, unpinned, refuse, logger));
|
||||
assertNull(NoiseNatives.install(cache, "macos-x86_64", bundled, refuse, logger));
|
||||
}
|
||||
assertTrue(errors.isEmpty());
|
||||
}
|
||||
|
||||
private NoiseNatives.Fetcher serving(List<URI> requested, Map<URI, byte[]> overrides) {
|
||||
return (uri, limit) -> {
|
||||
requested.add(uri);
|
||||
return overrides.getOrDefault(uri, NATIVE);
|
||||
};
|
||||
}
|
||||
|
||||
private String manifest(String commit) {
|
||||
return "commit=" + commit + "\nsource=shared/native/noise/prebuilt\nplatforms=" + PLATFORM + "\n"
|
||||
+ PLATFORM + ".file=" + FILE + "\n" + PLATFORM + ".size=" + NATIVE.length + "\n"
|
||||
+ PLATFORM + ".sha256=" + sha256(NATIVE) + "\n" + PLATFORM + ".blob=" + blob(NATIVE) + "\n";
|
||||
}
|
||||
|
||||
private URLClassLoader resources(String manifest, Map<String, byte[]> extra) throws IOException {
|
||||
Path root = temporaryFolder.newFolder().toPath();
|
||||
if (manifest != null) {
|
||||
Path file = root.resolve(NoiseNatives.MANIFEST);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, manifest, StandardCharsets.UTF_8);
|
||||
}
|
||||
for (Map.Entry<String, byte[]> entry : extra.entrySet()) {
|
||||
Path file = root.resolve(entry.getKey());
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, entry.getValue());
|
||||
}
|
||||
return new URLClassLoader(new URL[]{root.toUri().toURL()}, null);
|
||||
}
|
||||
|
||||
private static String sha256(byte[] bytes) {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static String blob(byte[] bytes) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-1");
|
||||
digest.update(("blob " + bytes.length + "\0").getBytes(StandardCharsets.US_ASCII));
|
||||
return HexFormat.of().formatHex(digest.digest(bytes));
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,7 @@ public class SwallowedFailurePolicyTest {
|
||||
"src/main/java/art/arcane/iris/world/history",
|
||||
"../spi/src/main/java",
|
||||
"../adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java",
|
||||
"../adapters/bukkit/plugin/src/main/java/art/arcane/iris/IrisRuntime.java",
|
||||
"../adapters/bukkit/plugin/src/main/java/art/arcane/iris/world/PendingWorldReplacementManager.java"
|
||||
);
|
||||
private static final Pattern IGNORED_CATCH = Pattern.compile("^\\s*}?\\s*catch \\([^)]*\\)\\s*\\{\\s*$");
|
||||
|
||||
@@ -19,7 +19,7 @@ public class GpuLibraryTest {
|
||||
public void missingNativeLibrariesUseSoftwareEvenWhenBindingClassesExist() throws Exception {
|
||||
List<URL> classpath = new ArrayList<>();
|
||||
for (String entry : System.getProperty("java.class.path").split(Pattern.quote(File.pathSeparator))) {
|
||||
if (!entry.contains("natives-")) {
|
||||
if (!new File(entry).getName().contains("-natives-")) {
|
||||
classpath.add(new File(entry).toURI().toURL());
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public class GpuLibraryTest {
|
||||
while (loader != null) {
|
||||
if (loader instanceof URLClassLoader urls) {
|
||||
for (URL url : urls.getURLs()) {
|
||||
if (!url.getPath().contains("natives-")) {
|
||||
if (!new File(url.getPath()).getName().contains("-natives-")) {
|
||||
classpath.add(url);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user