Optimize launcher preparation with precompiled, batched exporters

Compile and validate original exporter bundles during release builds, cache development compilation, and reuse initialized JVMs and collision data during preparation. Keep legacy preparers compatible while current releases need only a Java runtime.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
rdbtCVS
2026-10-25 23:11:23 +00:00
parent d58d26c793
commit f45e3f1237
20 changed files with 810 additions and 78 deletions
+218
View File
@@ -0,0 +1,218 @@
//! Only original Horizon classes are packaged. The pinned jars remain player supplied.
use crate::*;
const SETTINGS: &str = "exporters-v1 --release -proc:none -encoding UTF-8";
const SERVER: &[&str] = &[
"VanillaHeightmapOracle",
"VanillaBlockLandingOracle",
"VanillaEntityAttributeOracle",
"VanillaPlayerHealthOracle",
"VanillaDamageSourceOracle",
"VanillaCollisionOracle",
"VanillaFaceVisibilityOracle",
"VanillaGameplayFactsExporter",
"VanillaEntityTypesExporter",
"VanillaBlockBehaviourExporter",
"VanillaCommandParseOracle",
"VanillaCreativeTabsExporter",
"VanillaSimpleBlockOracle",
"VanillaStructureBlockExporter",
"PrepareWorker",
];
const CLIENT: &[&str] = &[
"VanillaBlockStateBindingOracle",
"VanillaEntityModelExporter",
"VanillaMobDataExporter",
"PrepareWorker",
];
fn files(dir: &Path) -> Result<Vec<PathBuf>, String> {
let mut result = Vec::new();
for entry in fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? {
let path = entry.map_err(|e| e.to_string())?.path();
if path.is_dir() {
result.extend(files(&path)?);
} else {
result.push(path);
}
}
result.sort();
Ok(result)
}
// research-lock pins both jars and every accepted client manifest (which pins its libraries).
// artifacts::verify/client_libraries check those dependencies before any bundle is used.
fn key(root: &Path) -> Result<String, String> {
let mut hash = sha2::Sha256::new();
hash.update(SETTINGS);
// The launcher's bundled preparer may differ from the selected game's. Hash that
// version's compiler settings so a newer release still selects a runtime correctly.
let compiler = fs::read_to_string(root.join("crates/horizon-prepare/src/exporters.rs"))
.unwrap_or_else(|_| include_str!("exporters.rs").into());
hash.update(compiler.replace('\r', ""));
let mut sources = files(&root.join(PARITY))?;
sources.retain(|p| p.extension().is_some_and(|e| e == "java"));
sources.push(root.join("research-lock.json"));
for path in sources {
let data: Vec<_> = read(&path)?.into_iter().filter(|b| *b != b'\r').collect();
hash.update(format!(
"{}\0{}\0",
relative_display(&path, root)?.replace('\\', "/"),
data.len()
));
hash.update(data);
}
Ok(hex(&hash.finalize()))
}
fn outputs(dir: &Path) -> Result<Value, String> {
let mut hashes = Value::Object(Vec::new());
for path in files(dir)? {
if path.extension().is_some_and(|e| e == "class") {
let name = relative_display(&path, dir)?.replace('\\', "/");
// javac's sourcepath contains our sources only; enforce that at packaging too.
if !name.starts_with("server/dev/horizonlab/parity/")
&& !name.starts_with("client/dev/horizonlab/parity/")
{
return Err(format!("Non-Horizon class in exporter bundle: {name}"));
}
hashes.insert(&name, Value::Str(digest(&path, "sha256")?));
}
}
Ok(hashes)
}
fn valid(dir: &Path, key: &str) -> bool {
let Ok(manifest) = read_json(&dir.join("manifest.json")) else {
return false;
};
manifest.get("key").and_then(Value::as_str) == Some(key)
&& outputs(dir).is_ok_and(|hashes| {
!hashes.as_object().unwrap().is_empty() && manifest.get("classes") == Some(&hashes)
})
}
/// Whether the version ships a matching, intact bundle and needs only a Java runtime.
pub fn available(root: &Path) -> bool {
key(root).is_ok_and(|key| valid(&root.join("exporters"), &key))
}
pub(crate) fn classes(run: &Run) -> Result<PathBuf, String> {
let key = key(&run.root)?;
let shipped = run.root.join("exporters");
if valid(&shipped, &key) {
return Ok(shipped);
}
let cached = run.local.join("exporters").join(&key);
if valid(&cached, &key) {
return Ok(cached);
}
// Build privately: an interrupted compiler or another preparer cannot publish partial classes.
let destination = cached;
let cached = run
.local
.join("exporters")
.join(format!(".{key}-{}", std::process::id()));
if cached.exists() {
fs::remove_dir_all(&cached).map_err(|e| e.to_string())?;
}
mkdir(&cached)?;
let jdk = java::find(run.java_major, &[run.jdk.home()])?;
for (side, mains, cp) in [
("server", SERVER, &run.server_classpath),
("client", CLIENT, &run.client_classpath),
] {
(run.log)(&format!("Compiling {side} exporters (shared helpers once)"));
let classes = cached.join(side);
mkdir(&classes)?;
let log = run.log_file(&cached.join(format!("{side}.log")))?;
let mut args = vec![
"-encoding".into(),
"UTF-8".into(),
"-cp".into(),
cp.clone(),
"-sourcepath".into(),
arg(&run.root.join("mods/horizon/src/test/java")),
"-d".into(),
arg(&classes),
];
args.extend(mains.iter().map(|n| arg(&run.oracle(&format!("{n}.java")))));
jdk.javac(run.java_major, &args, &log)?;
let validate = vec![
"-Xverify:all".into(),
"-cp".into(),
format!(
"{}{}{}",
classes.display(),
if cfg!(windows) { ";" } else { ":" },
cp
),
"dev.horizonlab.parity.PrepareWorker".into(),
"validate".into(),
arg(&classes),
];
// No exporter executes here: resolve every class and its signatures against pinned jars.
run.jdk.java(&validate, None, &log)?;
}
let manifest = Value::Object(vec![
("key".into(), Value::Str(key.clone())),
("classes".into(), outputs(&cached)?),
]);
write_json(&cached.join("manifest.json"), &manifest)?;
if valid(&destination, &key) {
fs::remove_dir_all(&cached).map_err(|e| e.to_string())?;
} else {
if destination.exists() {
fs::remove_dir_all(&destination).map_err(|e| e.to_string())?;
}
fs::rename(&cached, &destination).map_err(|e| e.to_string())?;
}
Ok(destination)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundles_invalidate_sources_pins_and_damaged_classes() {
let root = std::env::temp_dir().join(format!("prepare-bundle-{}", std::process::id()));
let source = root.join(PARITY).join("VanillaHeightmapOracle.java");
mkdir(source.parent().unwrap()).unwrap();
write(&source, b"original\n").unwrap();
let compiler = root.join("crates/horizon-prepare/src/exporters.rs");
mkdir(compiler.parent().unwrap()).unwrap();
write(&compiler, b"--release 25 -proc:none").unwrap();
write(&root.join("research-lock.json"), b"pins").unwrap();
let original = key(&root).unwrap();
write(&compiler, b"--release 26 -proc:none").unwrap();
assert_ne!(key(&root).unwrap(), original);
write(&compiler, b"--release 25 -proc:none").unwrap();
write(&source, b"original\r\n").unwrap();
assert_eq!(key(&root).unwrap(), original);
write(&source, b"changed").unwrap();
assert_ne!(key(&root).unwrap(), original);
write(&source, b"original\n").unwrap();
write(&root.join("research-lock.json"), b"new dependencies").unwrap();
assert_ne!(key(&root).unwrap(), original);
write(&root.join("research-lock.json"), b"pins").unwrap();
let bundle = root.join("exporters");
let class = bundle.join("server/dev/horizonlab/parity/Helper.class");
mkdir(class.parent().unwrap()).unwrap();
write(&class, b"compiled").unwrap();
write_json(
&bundle.join("manifest.json"),
&Value::Object(vec![
("key".into(), Value::Str(original)),
("classes".into(), outputs(&bundle).unwrap()),
]),
)
.unwrap();
assert!(available(&root));
write(&class, b"damaged").unwrap();
assert!(!available(&root));
fs::remove_file(&class).unwrap();
assert!(!available(&root));
fs::remove_dir_all(root).unwrap();
}
}
+28 -17
View File
@@ -1,4 +1,4 @@
//! The JDK that compiles and runs the vanilla exporters. They call Mojang's own code, so they
//! Java discovery and execution for the vanilla exporters. They call Mojang's own code, so they
//! stay Java; everything around them is here.
use std::ffi::OsStr;
@@ -15,7 +15,7 @@ pub struct Jdk {
const TIMEOUT: Duration = Duration::from_secs(3600);
/// Exporters and JDK probes write to pipes or log files: on Windows they open no terminal.
fn command(program: impl AsRef<OsStr>) -> Command {
pub(crate) fn command(program: impl AsRef<OsStr>) -> Command {
let command = Command::new(program);
#[cfg(windows)]
let command = {
@@ -56,9 +56,9 @@ fn without_verbatim(path: PathBuf) -> PathBuf {
/// Resolve compiler symlinks before picking its sibling runtime. The first `java` on the
/// PATH may be an older, runtime-only install; it must not be paired with a newer `javac`.
fn path_jdks(path: &OsStr) -> Vec<PathBuf> {
fn path_homes(path: &OsStr, tool: &str) -> Vec<PathBuf> {
std::env::split_paths(path)
.map(|dir| executable(&dir, "javac"))
.map(|dir| executable(&dir, tool))
.filter(|javac| javac.is_file())
.map(real_path)
.filter_map(|javac| {
@@ -162,7 +162,7 @@ fn jdk_parents() -> Vec<PathBuf> {
/// The JDKs (folders with `bin/javac`) one level below `parents`; a macOS bundle's home is
/// its `Contents/Home`. Those named for `major` come first, then the others newest name first.
fn installed_jdks(parents: &[PathBuf], major: i64) -> Vec<PathBuf> {
fn installed_jdks(parents: &[PathBuf], major: i64, tool: &str) -> Vec<PathBuf> {
let mut homes: Vec<PathBuf> = parents
.iter()
.filter_map(|parent| fs::read_dir(parent).ok())
@@ -176,7 +176,7 @@ fn installed_jdks(parents: &[PathBuf], major: i64) -> Vec<PathBuf> {
entry.path()
}
})
.filter(|home| executable(&home.join("bin"), "javac").is_file())
.filter(|home| executable(&home.join("bin"), tool).is_file())
.collect();
let named = |home: &Path| {
home.iter().any(|part| {
@@ -191,8 +191,7 @@ fn installed_jdks(parents: &[PathBuf], major: i64) -> Vec<PathBuf> {
}
/// The Java runtimes the official launcher downloaded into `runtime` (a game directory's
/// `runtime` folder: `<component>/<platform>/<component>/`, a macOS one in `jre.bundle`). Mojang's
/// runtimes are whole JDKs, javac included, so a player who has run Minecraft has one already.
/// `runtime` folder: `<component>/<platform>/<component>/`, a macOS one in `jre.bundle`).
pub fn minecraft_runtimes(runtime: &Path) -> Vec<PathBuf> {
let children = |dir: &Path| -> Vec<PathBuf> {
let mut paths: Vec<PathBuf> = fs::read_dir(dir)
@@ -206,7 +205,7 @@ pub fn minecraft_runtimes(runtime: &Path) -> Vec<PathBuf> {
for platform in children(&component) {
let home = platform.join(component.file_name().unwrap_or_default());
for home in [home.join("jre.bundle/Contents/Home"), home] {
if executable(&home.join("bin"), "javac").is_file() {
if executable(&home.join("bin"), "java").is_file() {
homes.push(home);
break;
}
@@ -221,8 +220,18 @@ pub fn minecraft_runtimes(runtime: &Path) -> Vec<PathBuf> {
/// `/usr/libexec/java_home -v <major>` reports, else the homes in `more` (the launcher's pick,
/// Minecraft's own runtimes), else the folders installers use (`jdk_parents`).
pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
find_tools(major, more, true)
}
/// Finds a compatible runtime; precompiled exporters do not need javac.
pub fn find_runtime(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
find_tools(major, more, false)
}
fn find_tools(major: i64, more: &[PathBuf], compiler: bool) -> Result<Jdk, String> {
let tool = if compiler { "javac" } else { "java" };
let need = format!(
"Java {major} is needed (a JDK with javac, e.g. Eclipse Temurin {major}). \
"Java {major} is needed ({tool}, e.g. Eclipse Temurin {major}). \
Install it, or set JAVA_HOME to it, and try again."
);
let mut candidates = Vec::new();
@@ -235,7 +244,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
));
}
if let Some(path) = std::env::var_os("PATH") {
for home in path_jdks(&path) {
for home in path_homes(&path, tool) {
let bin = home.join("bin");
candidates.push((executable(&bin, "javac"), executable(&bin, "java"), "PATH"));
}
@@ -265,7 +274,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
"Minecraft's Java",
));
}
for home in installed_jdks(&jdk_parents(), major) {
for home in installed_jdks(&jdk_parents(), major, tool) {
let bin = home.join("bin");
candidates.push((
executable(&bin, "javac"),
@@ -275,15 +284,16 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
}
let mut problems = Vec::new();
for (javac, java, from) in candidates {
if !javac.is_file() || !java.is_file() {
if (compiler && !javac.is_file()) || !java.is_file() {
problems.push(format!(
"{from} ({}) has no javac and java",
"{from} ({}) has no compatible Java tools",
javac.parent().unwrap().display()
));
continue;
}
let checked = [(&javac, "javac"), (&java, "java")]
.into_iter()
.filter(|(_, name)| compiler || *name == "java")
.try_for_each(|(program, name)| {
let found = tool_major(program, name)?;
if i64::from(found) >= major {
@@ -298,7 +308,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
}
}
if problems.is_empty() {
Err(format!("{need} No javac was found."))
Err(format!("{need} No {tool} was found."))
} else {
Err(format!("{need} Found: {}.", problems.join("; ")))
}
@@ -317,7 +327,7 @@ pub fn classpath<'a>(paths: impl IntoIterator<Item = &'a Path>) -> String {
impl Jdk {
/// The JDK's home, the folder above `bin` (what `JAVA_HOME` names).
pub fn home(&self) -> PathBuf {
self.javac
self.java
.parent()
.and_then(Path::parent)
.map(Path::to_path_buf)
@@ -424,6 +434,7 @@ mod tests {
dir.join("missing"),
],
25,
"javac",
);
assert_eq!(
found,
@@ -445,7 +456,7 @@ mod tests {
let make = |home: PathBuf, javac: bool| {
fs::create_dir_all(home.join("bin")).unwrap();
if javac {
fs::write(executable(&home.join("bin"), "javac"), b"").unwrap();
fs::write(executable(&home.join("bin"), "java"), b"").unwrap();
}
home
};
+48 -37
View File
@@ -11,11 +11,13 @@
//! run, keyed by the sha256 of their inputs and outputs recorded in the manifest, as before.
pub mod artifacts;
pub mod exporters;
mod inventory;
pub mod java;
pub mod pyjson;
mod sounds;
mod survival;
mod worker;
pub use sounds::{fonts, languages, packs, panorama, sounds, BUILT_IN_PACKS};
@@ -65,7 +67,7 @@ pub fn sources_sha256(crate_dir: &Path) -> Option<String> {
pub struct Options {
/// The version folder (a release folder, or a checkout): research-lock.json, the exporters'
/// Java sources, and `.local/` where everything is written.
/// Java sources, optional precompiled `exporters/`, and `.local/` where everything is written.
pub root: PathBuf,
/// Import the pinned game files from the player's own copy first (`--prepare`).
pub import: bool,
@@ -74,7 +76,7 @@ pub struct Options {
pub minecraft_dir: Option<PathBuf>,
/// The pinned server jar the player downloaded (`--server-jar`, else HORIZON_SERVER_JAR).
pub server_jar: Option<PathBuf>,
/// The JDK to try after JAVA_HOME and the PATH (the launcher's pick, e.g. Minecraft's
/// The Java runtime to try after JAVA_HOME and the PATH (the launcher's pick, e.g. Minecraft's
/// own Java it downloaded from Mojang).
pub java_home: Option<PathBuf>,
}
@@ -293,6 +295,8 @@ struct Run<'a> {
server_classpath: String,
/// The client jar and its libraries: the classpath of the client-side exporters.
client_classpath: String,
bundles: std::cell::OnceCell<PathBuf>,
workers: std::cell::RefCell<[Option<worker::Worker>; 2]>,
previous: Value,
origin: Value,
log: Log<'a>,
@@ -301,6 +305,13 @@ struct Run<'a> {
const PARITY: &str = "mods/horizon/src/test/java/dev/horizonlab/parity";
impl Run<'_> {
fn bundle(&self) -> Result<&Path, String> {
if self.bundles.get().is_none() {
self.bundles.set(exporters::classes(self)?).unwrap();
}
Ok(self.bundles.get().unwrap())
}
fn oracle(&self, name: &str) -> PathBuf {
self.root.join(PARITY).join(name)
}
@@ -333,33 +344,31 @@ impl Run<'_> {
fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))
}
/// `javac --release <major> -proc:none -cp <classpath> [extra] -d <classes> <sources>`.
fn compile(
&self,
classpath: &str,
extra: &[String],
classes: &Path,
sources: &[&Path],
log: &fs::File,
) -> Result<(), String> {
let mut args = vec!["-cp".to_string(), classpath.to_string()];
args.extend_from_slice(extra);
args.push("-d".into());
args.push(classes.display().to_string());
args.extend(sources.iter().map(|s| s.display().to_string()));
self.jdk.javac(self.java_major, &args, log)
}
/// `java -Xmx<heap> -cp <classes>:<classpath> dev.horizonlab.parity.<main> <args>`.
fn run(
&self,
heap: &str,
classes: &Path,
classpath: &str,
main: &str,
args: &[String],
log: &fs::File,
log_path: &Path,
) -> Result<(), String> {
let side = usize::from(classpath == self.client_classpath);
let classes = self
.bundle()?
.join(if side == 1 { "client" } else { "server" });
if !matches!(
main,
"VanillaCommandParseOracle" | "VanillaCreativeTabsExporter"
) && std::env::var_os("HORIZON_PREPARE_ISOLATED").is_none()
{
let mut workers = self.workers.borrow_mut();
if workers[side].is_none() {
workers[side] = Some(worker::Worker::new(self, &classes, classpath)?);
}
return workers[side].as_mut().unwrap().run(main, args, log_path);
}
let separator = if cfg!(windows) { ";" } else { ":" };
let mut all = vec![
format!("-Xmx{heap}"),
@@ -371,7 +380,7 @@ impl Run<'_> {
self.jdk.java(&all, None, log)
}
/// Compiles `sources` into `classes` and runs each of `mains` with `args`, their output in
/// Runs each exporter from the verified shared bundle, with output in
/// the log at `log`: the shape of every exporter step.
#[allow(clippy::too_many_arguments)]
fn export(
@@ -379,7 +388,7 @@ impl Run<'_> {
what: &str,
classpath: &str,
classes: &Path,
sources: &[&Path],
_sources: &[&Path],
mains: &[&str],
heap: &str,
args: &[String],
@@ -389,10 +398,8 @@ impl Run<'_> {
mkdir(classes)?;
let file = self.log_file(log)?;
let fail = |e: String| format!("{e} while exporting {what}; see {}", log.display());
self.compile(classpath, &[], classes, sources, &file)
.map_err(fail)?;
for main in mains {
self.run(heap, classes, classpath, main, args, &file)
self.run(heap, classpath, main, args, &file, log)
.map_err(fail)?;
}
Ok(())
@@ -401,6 +408,15 @@ impl Run<'_> {
/// Prepares the resources; returns their folder (`.local/horizon-client/<version>`).
pub fn prepare(options: &Options, log: Log) -> Result<PathBuf, String> {
prepare_impl(options, log, false)
}
/// Release build tool: compile and link-check only Horizon's original exporter classes.
pub fn compile_exporters(options: &Options, log: Log) -> Result<PathBuf, String> {
prepare_impl(options, log, true)
}
fn prepare_impl(options: &Options, log: Log, compile_only: bool) -> Result<PathBuf, String> {
let root = &std::path::absolute(&options.root)
.map_err(|e| format!("{}: {e}", options.root.display()))?;
let lock = artifacts::Lock::read(root)?;
@@ -409,7 +425,7 @@ pub fn prepare(options: &Options, log: Log) -> Result<PathBuf, String> {
homes.extend(java::minecraft_runtimes(
&artifacts::minecraft_dir(options.minecraft_dir.as_deref()).join("runtime"),
));
let jdk = java::find(lock.java_major, &homes)?;
let jdk = java::find_runtime(lock.java_major, &homes)?;
if options.import && !artifacts::reuse_imported(root, log)? {
artifacts::import(
root,
@@ -456,10 +472,15 @@ pub fn prepare(options: &Options, log: Log) -> Result<PathBuf, String> {
client: found.jars["client"].clone(),
server_classpath: classpath_join(&found.jars["server"], &found.libraries),
client_classpath: classpath_join(&found.jars["client"], &client_libraries),
bundles: std::cell::OnceCell::new(),
workers: std::cell::RefCell::new([None, None]),
previous,
origin,
log,
};
if compile_only {
return Ok(run.bundle()?.to_path_buf());
}
steps(&run, &lock, &oracle, options.minecraft_dir.as_deref())?;
log(&format!(
"Prepared Horizon native-client resources: {}",
@@ -1117,7 +1138,6 @@ fn prepare_worldgen(run: &Run) -> Result<(), String> {
/// whose blocks are checked for survival or support (trees, flowers, grass, kelp, ...).
fn export_block_behavior(run: &Run, export: &Path) -> Result<(), String> {
(run.log)("Exporting block behavior (VanillaSimpleBlockOracle)");
let tests = run.root.join("mods/horizon/src/test/java");
let classes = export.join("classes");
mkdir(&classes)?;
let log_path = export.join("export.log");
@@ -1128,22 +1148,13 @@ fn export_block_behavior(run: &Run, export: &Path) -> Result<(), String> {
log_path.display()
)
};
// The oracle's helper classes are compiled on demand from the source path.
run.compile(
&run.server_classpath,
&["-sourcepath".into(), arg(&tests)],
&classes,
&[&tests.join("dev/horizonlab/parity/VanillaSimpleBlockOracle.java")],
&log,
)
.map_err(fail)?;
run.run(
"1G",
&classes,
&run.server_classpath,
"VanillaSimpleBlockOracle",
&["export".into(), arg(export)],
&log,
&log_path,
)
.map_err(fail)?;
let rules = survival::bind_definitions(
+7 -3
View File
@@ -16,6 +16,7 @@ const HELP: &str = "\
horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition
Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH]
horizon-prepare compile-exporters [--root PATH]
horizon-prepare sounds [--minecraft-dir PATH] [--root PATH]
horizon-prepare panorama [--minecraft-dir PATH] [--root PATH]
horizon-prepare fonts [--minecraft-dir PATH] [--root PATH]
@@ -30,8 +31,9 @@ Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [-
--root PATH The Horizon folder to prepare (default: the folder this program is
in, else the nearest folder above the current one with research-lock.json)
Needs Minecraft played once from the official launcher, and Java (a JDK) of the version
research-lock.json pins: JAVA_HOME, else javac and java on the PATH.
Needs Minecraft played once from the official launcher, and Java of the version
research-lock.json pins. Releases use a runtime; development or changed exporters need a JDK.
compile-exporters builds and validates a release bundle from the already imported pinned jars.
The resources go to <root>/.local/horizon-client/<version>; pass that to horizon-client --resources.
horizon-prepare panorama repairs the classic menu background in existing resources without Java.
@@ -73,7 +75,7 @@ fn main() -> ExitCode {
let assets = args.next_if(|a| {
matches!(
a.to_str(),
Some("sounds" | "panorama" | "fonts" | "packs" | "languages")
Some("sounds" | "panorama" | "fonts" | "packs" | "languages" | "compile-exporters")
)
});
while let Some(arg) = args.next() {
@@ -132,6 +134,8 @@ fn main() -> ExitCode {
let _ = out.flush();
};
let result = match assets.as_deref().and_then(|a| a.to_str()) {
Some("compile-exporters") => horizon_prepare::compile_exporters(&options, &log)
.inspect(|dir| log(&dir.display().to_string())),
Some("sounds") => {
horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log)
}
+79
View File
@@ -0,0 +1,79 @@
//! A bounded request/reply channel to one initialized exporter JVM.
use crate::*;
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Stdio};
use std::sync::mpsc::{self, Receiver};
pub(crate) struct Worker {
child: Child,
input: ChildStdin,
replies: Receiver<std::io::Result<String>>,
}
impl Worker {
pub(crate) fn new(run: &Run, classes: &Path, cp: &str) -> Result<Self, String> {
let log = run.log_file(&run.local.join(format!(
"{}-worker.log",
classes.file_name().unwrap().to_string_lossy()
)))?;
let mut child = java::command(&run.jdk.java)
.args([
"-Xmx2G",
"-cp",
&format!(
"{}{}{}",
classes.display(),
if cfg!(windows) { ";" } else { ":" },
cp
),
"dev.horizonlab.parity.PrepareWorker",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(log)
.spawn()
.map_err(|e| e.to_string())?;
let input = child.stdin.take().unwrap();
let output = child.stdout.take().unwrap();
let (send, replies) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(output).lines() {
if send.send(line).is_err() {
break;
}
}
});
Ok(Self {
child,
input,
replies,
})
}
pub(crate) fn run(&mut self, main: &str, args: &[String], log: &Path) -> Result<(), String> {
let task = Value::Array(vec![
Value::Str(arg(log)),
Value::Str(main.into()),
Value::Array(args.iter().cloned().map(Value::Str).collect()),
]);
writeln!(self.input, "{}", pyjson::dumps(&task, &pyjson::COMPACT))
.map_err(|e| e.to_string())?;
self.input.flush().map_err(|e| e.to_string())?;
let reply = self
.replies
.recv_timeout(std::time::Duration::from_secs(3600))
.map_err(|e| format!("Exporter JVM stopped or timed out: {e}"))?
.map_err(|e| e.to_string())?;
match pyjson::loads(&reply)?.as_str() {
Some("") => Ok(()),
_ => Err(format!("Exporter {main} failed: {reply}")),
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
+14 -2
View File
@@ -25,13 +25,23 @@ fn selects_a_compatible_compiler_and_runtime() {
assert!(error.contains(&format!("java {runtime} (")), "{error}");
return;
}
let jdk = java::find(25, &[]).unwrap();
let expected = root.join(if scenario == "target-release" {
let jdk = if scenario == "runtime-only" {
java::find_runtime(25, &[])
} else {
java::find(25, &[])
}
.unwrap();
let expected = root.join(if scenario == "runtime-only" {
"jre25"
} else if scenario == "target-release" {
"newer"
} else {
"jdk25"
});
for (actual, name) in [(&jdk.javac, "javac"), (&jdk.java, "java")] {
if scenario == "runtime-only" && name == "javac" {
continue;
}
assert_eq!(
fs::canonicalize(actual).unwrap(),
fs::canonicalize(tool(&expected.join("bin"), name)).unwrap()
@@ -64,6 +74,7 @@ fn selects_a_compatible_compiler_and_runtime() {
);
for (home, compiler, runtime) in [
("jre21", None, "21.0.1"),
("jre25", None, "25.0.1"),
("jdk21", Some("21.0.1"), "21.0.1"),
("jdk25", Some("25.0.1"), "25.0.1"),
("mixed", Some("25.0.1"), "21.0.1"),
@@ -83,6 +94,7 @@ fn selects_a_compatible_compiler_and_runtime() {
}
fs::write(root.join("failing/bin/java.exit"), "7").unwrap();
let scenarios = vec![
("runtime-only", Some("jre25"), vec!["jre21", "jre25"]),
("older-runtime", None, vec!["jre21", "jdk25"]),
("older-jdk", None, vec!["jdk21", "jdk25"]),
("incompatible-home", Some("mixed"), vec!["jdk25"]),