Download noise natives and language guides instead of bundling them in the Bukkit jar

This commit is contained in:
Brian Neumann-Fopiano committed 2026-11-01 16:29:20 -05:00
1 parent 1d23587b90
commit 714b4499b0
10 files changed
+952 -8

No files matched your search

@@ -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 {