Merge pull request #2098 from ludovic111/feat/launcher-mod-api-level

🤖 Agent: The launcher half of the mod API levels. CI is green on c8464c6bf, and the PR is now based on main after #2080 merged. Launcher tests pass, the new browser test included. The level mark is read from a real fast build of the game. Queued.
This commit is contained in:
Ludovic Marie
2026-10-26 12:22:55 +01:00
committed by GitHub
6 changed files with 162 additions and 27 deletions
+6
View File
@@ -4,7 +4,13 @@ mod game;
use horizon_client::{crash, logging};
/// The mod API level this game serves, kept in the program for the launcher
/// to read without running it (`horizon_mods::api_level::MARK`). `main`
/// reads it, so the linker keeps it.
static MOD_API_LEVEL: [u8; 27] = horizon_mods::api_level::MARK;
fn main() {
std::hint::black_box(&MOD_API_LEVEL);
horizon_client::telemetry::mark_start();
let args: Vec<String> = std::env::args().skip(1).collect();
let game_args = args.iter().take_while(|a| *a != "--dedicated");
+35
View File
@@ -48,6 +48,30 @@ pub const FUNCTIONS: [(&str, u32); 32] = [
("players.broadcast", 1),
];
/// What the game's program carries so the launcher can read its level
/// without running it: `horizon-mod-api-level:0001;` (four digits). A
/// program from before the mark serves level 0.
pub const MARK: [u8; 27] = {
let mut mark = *b"horizon-mod-api-level:0000;";
let mut level = LEVEL;
let mut i = 25;
while level > 0 {
mark[i] = b'0' + (level % 10) as u8;
level /= 10;
i -= 1;
}
mark
};
/// The level a program's bytes carry in their [`MARK`], if any.
pub fn read_mark(program: &[u8]) -> Option<u32> {
let prefix = &MARK[..22];
program
.windows(MARK.len())
.filter(|w| w.starts_with(prefix) && w[26] == b';')
.find_map(|w| std::str::from_utf8(&w[22..26]).ok()?.parse().ok())
}
/// A function's level; None for one this Horizon doesn't have.
pub fn level_of(function: &str) -> Option<u32> {
FUNCTIONS
@@ -134,6 +158,17 @@ mod tests {
assert!(FUNCTIONS.iter().any(|&(_, level)| level == LEVEL));
}
#[test]
fn the_mark_carries_the_level() {
assert_eq!(read_mark(&MARK), Some(LEVEL));
let mut program = b"\0\x7fELF horizon-mod-api-level: horizon-mod-api-level:".to_vec();
program.extend_from_slice(&MARK);
program.extend_from_slice(b"\0rest");
assert_eq!(read_mark(&program), Some(LEVEL));
assert_eq!(read_mark(b"horizon-mod-api-level:12;"), None);
assert_eq!(read_mark(b"no mark"), None);
}
#[test]
fn a_mod_needs_its_newest_function() {
assert_eq!(needed(["log.write", "hud.set-panel"]), (0, None));
+49
View File
@@ -422,6 +422,37 @@ pub fn version_dir(tag: &str) -> PathBuf {
const COMPLETE: &str = ".installed";
/// The mod API level of the game players run: the selected version's, else the newest installed
/// one's. None with no version installed: the launcher doesn't know yet which game will run mods.
pub fn game_mod_api_level() -> Option<u32> {
let installed = installed();
let tag = Settings::load()
.selected
.filter(|s| installed.contains(s))
.or_else(|| installed.into_iter().next())?;
Some(mod_api_level(&tag))
}
/// A game version's mod API level, read once from the mark its program carries
/// (`horizon_mods::api_level::MARK`). A program from before the mark serves level 0, the
/// contract of Horizon 0.2.67 and 0.2.68.
pub fn mod_api_level(tag: &str) -> u32 {
static LEVELS: Mutex<Vec<(String, u32)>> = Mutex::new(Vec::new());
let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(&(_, level)) = levels.iter().find(|(t, _)| t == tag) {
return level;
}
let level = program_mod_api_level(&version_dir(tag).join(CLIENT));
levels.push((tag.to_owned(), level));
level
}
/// The mod API level in the game program at `path`: its mark's, else 0.
fn program_mod_api_level(path: &Path) -> u32 {
let program = fs::read(path).unwrap_or_default();
horizon_mods::api_level::read_mark(&program).unwrap_or(0)
}
/// Installed versions, newest tag first.
pub fn installed() -> Vec<String> {
installed_in(&versions_dir())
@@ -2557,6 +2588,24 @@ mod tests {
use super::*;
use std::cmp::Ordering::*;
/// The game program's mod API level is its mark's; a program from before the mark (0.2.68
/// and older) or none at all serves level 0.
#[test]
fn a_game_program_says_its_mod_api_level() {
let dir = std::env::temp_dir().join(format!("horizon-api-level-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let marked = dir.join("marked");
let mut program = b"\x7fELF code code".to_vec();
program.extend_from_slice(b"horizon-mod-api-level:0007;");
fs::write(&marked, &program).unwrap();
let old = dir.join("old");
fs::write(&old, b"\x7fELF code without a mark").unwrap();
assert_eq!(program_mod_api_level(&marked), 7);
assert_eq!(program_mod_api_level(&old), 0);
assert_eq!(program_mod_api_level(&dir.join("missing")), 0);
fs::remove_dir_all(&dir).unwrap();
}
/// A preparation that reuses the imported game files still reads the assets from the
/// launcher that has them: a Prism Launcher instance's are in the launcher root, linked into
/// the official layout (jan.sonki on Discord: silent, grey title screen since 0.2.48).
+44 -17
View File
@@ -168,7 +168,14 @@ fn project_of(p: &index::Project) -> Option<Project> {
})
}
fn version_of(index: &Index, p: &index::Project, v: &index::Version) -> Version {
/// Version `v` of `p` as the browser shows it; blocked when taken down, or when it needs a newer
/// mod API level than `level`, the game's.
fn version_of(
index: &Index,
p: &index::Project,
v: &index::Version,
level: Option<u32>,
) -> Version {
Version {
id: v.version.clone(),
number: v.version.clone(),
@@ -187,7 +194,8 @@ fn version_of(index: &Index, p: &index::Project, v: &index::Version) -> Version
required: v.requires.iter().map(|r| r.id.clone()).collect(),
blocked: index
.revoked(&p.id, &v.file.sha256)
.map(|r| format!("taken down: {}", r.reason)),
.map(|r| format!("taken down: {}", r.reason))
.or_else(|| needs_newer(v, level).then(|| NEEDS_NEWER.to_string())),
}
}
@@ -254,9 +262,10 @@ impl Source for Registry {
let p = index
.project(&project.id)
.ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
let level = crate::backend::game_mod_api_level();
Ok(p.versions
.iter()
.map(|v| version_of(&index, p, v))
.map(|v| version_of(&index, p, v, level))
.collect())
}
@@ -378,20 +387,24 @@ fn relative(kind: Kind, id: &str, file_name: &str) -> Result<String, String> {
}
}
/// Installs a registry project into the game folder `home`: its newest version for this game,
/// downloaded into `mod-browser/downloads/`, checked against the index, then moved into place.
/// A mod is `horizon-mods/<id>.hmod`, turned on in `horizon-mods.txt`.
/// Installs a registry project into the game folder `home`: its newest version for this game that
/// the game the player runs can load, downloaded into `mod-browser/downloads/`, checked against
/// the index, then moved into place. A mod is `horizon-mods/<id>.hmod`, turned on in
/// `horizon-mods.txt`.
pub fn install(
project: &Project,
home: &Path,
progress: &dyn Fn(&str, f32),
) -> Result<Vec<installed::Entry>, String> {
install_from(&*index()?, local(), project, home, progress)
let level = crate::backend::game_mod_api_level();
install_from(&*index()?, local(), level, project, home, progress)
}
/// [`install`] from `index`, for a game serving mod API `level`.
fn install_from(
index: &Index,
local: bool,
level: Option<u32>,
project: &Project,
home: &Path,
progress: &dyn Fn(&str, f32),
@@ -399,27 +412,41 @@ fn install_from(
let p = index
.project(&project.id)
.ok_or_else(|| format!("{} isn't in Horizon's registry.", project.title))?;
let v = newest(index, p)?;
let v = newest(index, p, level)?;
install_version(index, local, p, v, home, progress).map(|e| vec![e])
}
/// A project's newest version for this game that wasn't taken down.
fn newest<'a>(index: &Index, p: &'a index::Project) -> Result<&'a index::Version, String> {
let mut taken_down = None;
/// A project's newest version for this game that wasn't taken down and that a game serving mod
/// API `level` runs (any, when the level isn't known).
fn newest<'a>(
index: &Index,
p: &'a index::Project,
level: Option<u32>,
) -> Result<&'a index::Version, String> {
let (mut taken_down, mut too_new) = (None, false);
for v in p.versions.iter().filter(|v| v.game == GAME) {
match index.revoked(&p.id, &v.file.sha256) {
None => return Ok(v),
Some(r) => {
taken_down.get_or_insert(r);
}
if let Some(r) = index.revoked(&p.id, &v.file.sha256) {
taken_down.get_or_insert(r);
} else if needs_newer(v, level) {
too_new = true;
} else {
return Ok(v);
}
}
Err(match taken_down {
_ if too_new => format!("{} {NEEDS_NEWER}: update it first.", p.name),
Some(r) => format!("{} was taken down: {}", p.name, r.reason),
None => format!("{} has no version for {GAME} to install.", p.name),
})
}
const NEEDS_NEWER: &str = "needs a newer Horizon than the game you play";
/// Whether version `v` calls mod API functions a game serving `level` doesn't have.
fn needs_newer(v: &index::Version, level: Option<u32>) -> bool {
matches!((v.api_level, level), (Some(needed), Some(level)) if needed > level)
}
/// Installs version `v` of the registry's mod, resource pack or shader pack `p` into the game
/// folder `home`.
fn install_version(
@@ -462,7 +489,7 @@ fn install_version(
return Err(format!("{relative} is already there: move it away first."));
}
let line = format!("{} {}", p.name, v.version);
let file = &version_of(index, p, v).files[0];
let file = &version_of(index, p, v, None).files[0];
let staging = home.join("mod-browser/downloads");
let path = fetch(file, &staging, local, &|f| progress(&line, f))?;
let trust = index::check_file(index, p, v, &path).inspect_err(|_| {
+1 -1
View File
@@ -84,7 +84,7 @@ fn install_in(
if p.kind != idx::Kind::Modpack {
return Err(format!("{} is a {}, not a modpack.", p.name, p.kind.name()));
}
let v = newest(index, p)?;
let v = newest(index, p, None)?;
let work = dir.join(&p.id);
let fresh = !work.exists();
let result = install_version_in(index, local, p, v, &work, progress);
+27 -9
View File
@@ -59,7 +59,7 @@ fn installs_checked_turns_on_and_removes() {
let index = sample();
let home = scratch("install");
let p = hud(&index);
let done = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
let done = install_from(&index, true, None, &p, &home, &|_, _| {}).unwrap();
assert_eq!(done[0].file, "horizon-mods/coords_hud.hmod");
assert_eq!(done[0].verdict.as_deref(), Some("Verified"));
assert!(done[0].checksum.starts_with("SHA-256:e1135345"));
@@ -73,7 +73,7 @@ fn installs_checked_turns_on_and_removes() {
0
);
// Installed already: nothing to do.
let again = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
let again = install_from(&index, true, None, &p, &home, &|_, _| {}).unwrap();
assert_eq!(again, done);
let mut revoked = index.clone();
@@ -102,7 +102,7 @@ fn installs_a_shader_pack_into_shaderpacks() {
let home = scratch("shader");
let p = project_of(index.project("glow").unwrap()).unwrap();
assert_eq!(p.support(), super::super::Support::Works);
let done = install_from(&index, true, &p, &home, &|_, _| {}).unwrap();
let done = install_from(&index, true, None, &p, &home, &|_, _| {}).unwrap();
assert_eq!(done[0].file, "shaderpacks/glow-1.0.0.hshader");
assert_eq!(done[0].kind, Kind::Shader);
assert!(home.join("shaderpacks/glow-1.0.0.hshader").is_file());
@@ -123,7 +123,7 @@ fn installs_a_shader_pack_into_shaderpacks() {
assert!(!home.join("shaderpacks/glow-1.0.0.hshader").exists());
// A file of the same name the registry didn't put there is left alone.
fs::write(home.join("shaderpacks/glow-1.0.0.hshader"), b"mine").unwrap();
let e = install_from(&index, true, &p, &home, &|_, _| {}).unwrap_err();
let e = install_from(&index, true, None, &p, &home, &|_, _| {}).unwrap_err();
assert_eq!(
e,
"shaderpacks/glow-1.0.0.hshader is already there: move it away first."
@@ -140,15 +140,15 @@ fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() {
let mut tampered = index.clone();
let cozy = tampered.projects[1].versions[0].file.url.clone();
tampered.projects[0].versions[0].file.url = cozy;
let e = install_from(&tampered, true, &p, &home, &|_, _| {}).unwrap_err();
let e = install_from(&tampered, true, None, &p, &home, &|_, _| {}).unwrap_err();
assert!(e.contains("larger than its source says"), "{e}");
assert!(!home.join("horizon-mods").exists());
let e = install_from(&index, false, &p, &home, &|_, _| {}).unwrap_err();
let e = install_from(&index, false, None, &p, &home, &|_, _| {}).unwrap_err();
assert!(e.contains("file servers"), "{e}");
fs::create_dir_all(home.join("horizon-mods/coords_hud")).unwrap();
let e = install_from(&index, true, &p, &home, &|_, _| {}).unwrap_err();
let e = install_from(&index, true, None, &p, &home, &|_, _| {}).unwrap_err();
assert!(e.contains("already in horizon-mods"), "{e}");
let mut taken_down = index.clone();
@@ -158,7 +158,7 @@ fn refuses_a_changed_file_a_taken_id_and_local_files_from_the_real_registry() {
reason: "Test.".into(),
date: String::new(),
});
let e = install_from(&taken_down, true, &p, &home, &|_, _| {}).unwrap_err();
let e = install_from(&taken_down, true, None, &p, &home, &|_, _| {}).unwrap_err();
assert_eq!(e, "Coordinates HUD was taken down: Test.");
fs::remove_dir_all(&home).unwrap();
}
@@ -175,7 +175,7 @@ fn registry_versions_run_when_made_for_this_game() {
let versions: Vec<Version> = p
.versions
.iter()
.map(|x| version_of(&index, p, x))
.map(|x| version_of(&index, p, x, None))
.collect();
assert_eq!(pick(Kind::Mod, &versions, false).unwrap().number, "0.1.0");
}
@@ -198,3 +198,21 @@ fn owner_links_only_take_github_logins() {
assert!(!github_login(bad), "{bad}");
}
}
/// A version that calls mod API functions the game doesn't have is marked and skipped.
#[test]
fn versions_for_a_newer_horizon_are_not_installed() {
let mut index = sample();
index.projects[0].versions[0].api_level = Some(1);
let p = index.project("coords_hud").unwrap();
let e = newest(&index, p, Some(0)).unwrap_err();
assert_eq!(
e,
"Coordinates HUD needs a newer Horizon than the game you play: update it first."
);
assert!(newest(&index, p, Some(1)).is_ok());
assert!(newest(&index, p, None).is_ok());
let v = version_of(&index, p, &p.versions[0], Some(0));
assert_eq!(v.blocked.as_deref(), Some(NEEDS_NEWER));
assert_eq!(version_of(&index, p, &p.versions[0], Some(1)).blocked, None);
}