mod executor;
mod fabric;
mod forge;
use std::{collections::BTreeMap, fmt, path::PathBuf, str::FromStr, sync::Arc};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::{
download::{CancellationToken, DownloadManager, DownloadRequest},
events::EventBus,
files::{FileHash, SafeRelativePath},
java::JavaManager,
minecraft::{Argument, VersionMetadata},
Error, Result,
};
pub(crate) use executor::{execute_loader_plan, load_loader_plan, write_loader_plan};
pub use fabric::FabricLoader;
pub use forge::ForgeLoader;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LoaderKind {
Fabric,
Forge,
NeoForge,
Quilt,
}
impl LoaderKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Fabric => "fabric",
Self::Forge => "forge",
Self::NeoForge => "neoforge",
Self::Quilt => "quilt",
}
}
}
impl fmt::Display for LoaderKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for LoaderKind {
type Err = Error;
fn from_str(value: &str) -> Result<Self> {
match value.to_ascii_lowercase().as_str() {
"fabric" => Ok(Self::Fabric),
"forge" => Ok(Self::Forge),
"neoforge" => Ok(Self::NeoForge),
"quilt" => Ok(Self::Quilt),
_ => Err(LoaderError::UnsupportedKind(value.to_owned()).into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderConfig {
pub kind: LoaderKind,
pub version: String,
}
impl LoaderConfig {
pub fn new(kind: LoaderKind, version: impl Into<String>) -> Result<Self> {
let value = Self {
kind,
version: version.into(),
};
value.validate()?;
Ok(value)
}
pub fn validate(&self) -> Result<()> {
if self.version.eq_ignore_ascii_case("latest")
|| self.version.is_empty()
|| self.version.len() > 128
|| !self.version.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+')
})
{
return Err(LoaderError::InvalidVersion(self.version.clone()).into());
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderIdentity {
pub kind: LoaderKind,
pub minecraft_version: String,
pub loader_version: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoaderFileKind {
Metadata,
Library,
Installer,
Processor,
Generated,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderDownload {
pub request: DownloadRequest,
pub kind: LoaderFileKind,
#[serde(default)]
pub classpath: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveEntryPlan {
pub archive: SafeRelativePath,
pub entry: String,
pub destination: SafeRelativePath,
pub expected_hash: Option<FileHash>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum ProcessorArgument {
Literal(String),
CacheRoot,
CachePath(SafeRelativePath),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessorOutput {
pub path: SafeRelativePath,
pub expected_size: Option<u64>,
pub expected_hash: Option<FileHash>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessorPlan {
pub id: String,
pub jar: SafeRelativePath,
pub classpath: Vec<SafeRelativePath>,
pub arguments: Vec<ProcessorArgument>,
pub outputs: Vec<ProcessorOutput>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LoaderPlan {
pub format_version: u32,
pub identity: LoaderIdentity,
pub version_id: String,
pub downloads: Vec<LoaderDownload>,
pub archive_entries: Vec<ArchiveEntryPlan>,
pub processors: Vec<ProcessorPlan>,
pub classpath_additions: Vec<SafeRelativePath>,
pub main_class: Option<String>,
pub jvm_arguments: Vec<Argument>,
pub game_arguments: Vec<Argument>,
pub minimum_java_major: Option<u16>,
}
impl LoaderPlan {
pub const FORMAT_VERSION: u32 = 1;
pub fn validate(&self) -> Result<()> {
if self.format_version != Self::FORMAT_VERSION {
return Err(Error::UnsupportedFormat {
kind: "loader plan",
version: self.format_version,
});
}
LoaderConfig::new(self.identity.kind, &self.identity.loader_version)?;
if self.identity.minecraft_version.is_empty() {
return Err(LoaderError::InvalidPlan("empty Minecraft version".into()).into());
}
if self.version_id.is_empty() || self.version_id.chars().any(char::is_control) {
return Err(LoaderError::InvalidPlan("invalid loader version id".into()).into());
}
if self
.main_class
.as_ref()
.is_some_and(|value| value.is_empty() || value.chars().any(char::is_control))
{
return Err(LoaderError::InvalidPlan("invalid main class".into()).into());
}
let mut destinations = std::collections::BTreeSet::new();
for download in &self.downloads {
if !destinations.insert(download.request.destination.clone()) {
return Err(
LoaderError::DuplicatePath(download.request.destination.to_string()).into(),
);
}
}
for extraction in &self.archive_entries {
if extraction.entry.is_empty()
|| extraction.entry.contains("..")
|| extraction.entry.contains('\\')
{
return Err(LoaderError::InvalidPlan("unsafe archive entry".into()).into());
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderVersion {
pub version: String,
pub stable: bool,
}
pub struct LoaderResolveContext<'a> {
pub downloads: &'a DownloadManager,
pub events: &'a EventBus,
pub cache_root: &'a std::path::Path,
pub base_version: Option<&'a VersionMetadata>,
pub cancellation: &'a CancellationToken,
pub offline: bool,
}
#[async_trait]
pub trait Loader: Send + Sync {
fn kind(&self) -> LoaderKind;
async fn versions(
&self,
minecraft_version: &str,
context: &LoaderResolveContext<'_>,
) -> Result<Vec<LoaderVersion>>;
async fn resolve(
&self,
config: &LoaderConfig,
minecraft_version: &str,
context: &LoaderResolveContext<'_>,
) -> Result<LoaderPlan>;
}
#[derive(Clone, Default)]
pub struct LoaderRegistry {
implementations: Arc<BTreeMap<LoaderKind, Arc<dyn Loader>>>,
}
impl fmt::Debug for LoaderRegistry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LoaderRegistry")
.field("kinds", &self.implementations.keys().collect::<Vec<_>>())
.finish()
}
}
impl LoaderRegistry {
#[must_use]
pub fn with_defaults() -> Self {
let mut implementations = BTreeMap::<LoaderKind, Arc<dyn Loader>>::new();
implementations.insert(LoaderKind::Fabric, Arc::new(FabricLoader));
implementations.insert(LoaderKind::Forge, Arc::new(ForgeLoader));
Self {
implementations: Arc::new(implementations),
}
}
pub fn get(&self, kind: LoaderKind) -> Result<&Arc<dyn Loader>> {
self.implementations
.get(&kind)
.ok_or_else(|| LoaderError::UnsupportedKind(kind.to_string()).into())
}
}
#[derive(Debug, Clone)]
pub struct LoaderManager {
registry: LoaderRegistry,
downloads: DownloadManager,
java: JavaManager,
events: EventBus,
cache_root: PathBuf,
}
impl LoaderManager {
pub(crate) fn new(
cache_root: PathBuf,
downloads: DownloadManager,
java: JavaManager,
events: EventBus,
) -> Self {
Self {
registry: LoaderRegistry::with_defaults(),
downloads,
java,
events,
cache_root,
}
}
#[must_use]
pub fn registry(&self) -> &LoaderRegistry {
&self.registry
}
pub async fn versions(
&self,
kind: LoaderKind,
minecraft_version: &str,
cancellation: &CancellationToken,
) -> Result<Vec<LoaderVersion>> {
self.events.emit(crate::CoreEvent::LoaderResolutionStarted {
loader: kind.to_string(),
minecraft_version: minecraft_version.to_owned(),
loader_version: None,
});
let context = LoaderResolveContext {
downloads: &self.downloads,
events: &self.events,
cache_root: &self.cache_root,
base_version: None,
cancellation,
offline: false,
};
let versions = self
.registry
.get(kind)?
.versions(minecraft_version, &context)
.await?;
self.events
.emit(crate::CoreEvent::LoaderResolutionCompleted {
loader: kind.to_string(),
minecraft_version: minecraft_version.to_owned(),
loader_version: versions
.first()
.map_or_else(String::new, |version| version.version.clone()),
downloads: 0,
processors: 0,
});
Ok(versions)
}
pub(crate) async fn resolve(
&self,
config: &LoaderConfig,
base_version: &VersionMetadata,
cancellation: &CancellationToken,
offline: bool,
) -> Result<LoaderPlan> {
config.validate()?;
self.events.emit(crate::CoreEvent::LoaderResolutionStarted {
loader: config.kind.to_string(),
minecraft_version: base_version.id.clone(),
loader_version: Some(config.version.clone()),
});
let context = LoaderResolveContext {
downloads: &self.downloads,
events: &self.events,
cache_root: &self.cache_root,
base_version: Some(base_version),
cancellation,
offline,
};
let plan = self
.registry
.get(config.kind)?
.resolve(config, &base_version.id, &context)
.await?;
plan.validate()?;
self.events
.emit(crate::CoreEvent::LoaderResolutionCompleted {
loader: config.kind.to_string(),
minecraft_version: base_version.id.clone(),
loader_version: plan.identity.loader_version.clone(),
downloads: plan.downloads.len() as u64,
processors: plan.processors.len() as u64,
});
Ok(plan)
}
pub(crate) fn java(&self) -> &JavaManager {
&self.java
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LoaderError {
#[error("loader `{0}` is not available in this CentralCore build")]
UnsupportedKind(String),
#[error("loader version `{0}` is not an exact portable version")]
InvalidVersion(String),
#[error("{loader} {version} is not compatible with Minecraft {minecraft}")]
VersionNotFound {
loader: LoaderKind,
minecraft: String,
version: String,
},
#[error("invalid loader plan: {0}")]
InvalidPlan(String),
#[error("loader plan contains duplicate destination `{0}`")]
DuplicatePath(String),
#[error("unsupported Forge installer profile spec {0}")]
UnsupportedForgeSpec(u32),
#[error("loader metadata is invalid: {0}")]
InvalidMetadata(String),
#[error("loader processor `{id}` exited with code {code:?}")]
ProcessorFailed { id: String, code: Option<i32> },
#[error("loader processor `{id}` did not produce a valid `{path}`")]
InvalidProcessorOutput { id: String, path: String },
#[error("loader plan is unavailable in the local cache")]
OfflinePlanUnavailable,
}
#[cfg(test)]
mod tests {
use super::*;
use url::Url;
fn plan() -> LoaderPlan {
LoaderPlan {
format_version: LoaderPlan::FORMAT_VERSION,
identity: LoaderIdentity {
kind: LoaderKind::Fabric,
minecraft_version: "1.20.4".into(),
loader_version: "0.19.5".into(),
},
version_id: "fabric-loader-0.19.5-1.20.4".into(),
downloads: Vec::new(),
archive_entries: Vec::new(),
processors: Vec::new(),
classpath_additions: Vec::new(),
main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()),
jvm_arguments: vec![Argument::Plain("-Dcentralcore.loader=true".into())],
game_arguments: Vec::new(),
minimum_java_major: Some(17),
}
}
fn download(id: &str) -> LoaderDownload {
LoaderDownload {
request: DownloadRequest {
id: id.into(),
source: Url::parse("https://example.test/library.jar").expect("URL"),
destination: SafeRelativePath::new("libraries/example/library.jar").expect("path"),
expected_size: Some(4),
expected_hash: None,
},
kind: LoaderFileKind::Library,
classpath: true,
}
}
#[test]
fn plan_round_trips_as_versioned_data() {
let plan = plan();
plan.validate().expect("valid plan");
let json = serde_json::to_vec(&plan).expect("serialize");
let decoded: LoaderPlan = serde_json::from_slice(&json).expect("deserialize");
assert_eq!(decoded, plan);
}
#[test]
fn plan_rejects_duplicate_destinations() {
let mut plan = plan();
plan.downloads = vec![download("first"), download("second")];
assert!(matches!(
plan.validate(),
Err(Error::LoaderPlan(LoaderError::DuplicatePath(_)))
));
}
#[test]
fn default_registry_contains_both_phase_five_loaders() {
let registry = LoaderRegistry::with_defaults();
assert!(registry.get(LoaderKind::Fabric).is_ok());
assert!(registry.get(LoaderKind::Forge).is_ok());
assert!(registry.get(LoaderKind::NeoForge).is_err());
assert!(registry.get(LoaderKind::Quilt).is_err());
}
}