Skip to main content

centralcore/loaders/
mod.rs

1//! Generic mod-loader planning, registry, execution, and persistence.
2
3mod executor;
4mod fabric;
5mod forge;
6
7use std::{collections::BTreeMap, fmt, path::PathBuf, str::FromStr, sync::Arc};
8
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11
12use crate::{
13    download::{CancellationToken, DownloadManager, DownloadRequest},
14    events::EventBus,
15    files::{FileHash, SafeRelativePath},
16    java::JavaManager,
17    minecraft::{Argument, VersionMetadata},
18    Error, Result,
19};
20
21pub(crate) use executor::{execute_loader_plan, load_loader_plan, write_loader_plan};
22pub use fabric::FabricLoader;
23pub use forge::ForgeLoader;
24
25/// Loader families understood by the public model.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum LoaderKind {
30    Fabric,
31    Forge,
32    NeoForge,
33    Quilt,
34}
35
36impl LoaderKind {
37    #[must_use]
38    pub const fn as_str(self) -> &'static str {
39        match self {
40            Self::Fabric => "fabric",
41            Self::Forge => "forge",
42            Self::NeoForge => "neoforge",
43            Self::Quilt => "quilt",
44        }
45    }
46}
47
48impl fmt::Display for LoaderKind {
49    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
50        formatter.write_str(self.as_str())
51    }
52}
53
54impl FromStr for LoaderKind {
55    type Err = Error;
56
57    fn from_str(value: &str) -> Result<Self> {
58        match value.to_ascii_lowercase().as_str() {
59            "fabric" => Ok(Self::Fabric),
60            "forge" => Ok(Self::Forge),
61            "neoforge" => Ok(Self::NeoForge),
62            "quilt" => Ok(Self::Quilt),
63            _ => Err(LoaderError::UnsupportedKind(value.to_owned()).into()),
64        }
65    }
66}
67
68/// Versioned loader selection attached to an instance.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct LoaderConfig {
71    pub kind: LoaderKind,
72    pub version: String,
73}
74
75impl LoaderConfig {
76    pub fn new(kind: LoaderKind, version: impl Into<String>) -> Result<Self> {
77        let value = Self {
78            kind,
79            version: version.into(),
80        };
81        value.validate()?;
82        Ok(value)
83    }
84
85    /// Validates a portable, exact loader version coordinate.
86    pub fn validate(&self) -> Result<()> {
87        if self.version.eq_ignore_ascii_case("latest")
88            || self.version.is_empty()
89            || self.version.len() > 128
90            || !self.version.bytes().all(|byte| {
91                byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+')
92            })
93        {
94            return Err(LoaderError::InvalidVersion(self.version.clone()).into());
95        }
96        Ok(())
97    }
98}
99
100/// Reproducible identity embedded in every loader plan.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102pub struct LoaderIdentity {
103    pub kind: LoaderKind,
104    pub minecraft_version: String,
105    pub loader_version: String,
106}
107
108/// Role of a loader-owned object in the managed-file index.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum LoaderFileKind {
112    Metadata,
113    Library,
114    Installer,
115    Processor,
116    Generated,
117}
118
119/// One cache download produced by a loader resolver.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct LoaderDownload {
122    pub request: DownloadRequest,
123    pub kind: LoaderFileKind,
124    #[serde(default)]
125    pub classpath: bool,
126}
127
128/// Exact archive member copied to a controlled cache-relative destination.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130pub struct ArchiveEntryPlan {
131    pub archive: SafeRelativePath,
132    pub entry: String,
133    pub destination: SafeRelativePath,
134    pub expected_hash: Option<FileHash>,
135}
136
137/// A processor argument already normalized by its loader implementation.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
140pub enum ProcessorArgument {
141    Literal(String),
142    CacheRoot,
143    CachePath(SafeRelativePath),
144}
145
146/// A file generated by a trusted loader processor.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148pub struct ProcessorOutput {
149    pub path: SafeRelativePath,
150    pub expected_size: Option<u64>,
151    pub expected_hash: Option<FileHash>,
152}
153
154/// One ordered Java operation emitted by an official loader implementation.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct ProcessorPlan {
157    pub id: String,
158    pub jar: SafeRelativePath,
159    pub classpath: Vec<SafeRelativePath>,
160    pub arguments: Vec<ProcessorArgument>,
161    pub outputs: Vec<ProcessorOutput>,
162}
163
164/// Generic, serializable overlay composed with a Vanilla installation.
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub struct LoaderPlan {
167    pub format_version: u32,
168    pub identity: LoaderIdentity,
169    pub version_id: String,
170    pub downloads: Vec<LoaderDownload>,
171    pub archive_entries: Vec<ArchiveEntryPlan>,
172    pub processors: Vec<ProcessorPlan>,
173    pub classpath_additions: Vec<SafeRelativePath>,
174    pub main_class: Option<String>,
175    pub jvm_arguments: Vec<Argument>,
176    pub game_arguments: Vec<Argument>,
177    pub minimum_java_major: Option<u16>,
178}
179
180impl LoaderPlan {
181    pub const FORMAT_VERSION: u32 = 1;
182
183    pub fn validate(&self) -> Result<()> {
184        if self.format_version != Self::FORMAT_VERSION {
185            return Err(Error::UnsupportedFormat {
186                kind: "loader plan",
187                version: self.format_version,
188            });
189        }
190        LoaderConfig::new(self.identity.kind, &self.identity.loader_version)?;
191        if self.identity.minecraft_version.is_empty() {
192            return Err(LoaderError::InvalidPlan("empty Minecraft version".into()).into());
193        }
194        if self.version_id.is_empty() || self.version_id.chars().any(char::is_control) {
195            return Err(LoaderError::InvalidPlan("invalid loader version id".into()).into());
196        }
197        if self
198            .main_class
199            .as_ref()
200            .is_some_and(|value| value.is_empty() || value.chars().any(char::is_control))
201        {
202            return Err(LoaderError::InvalidPlan("invalid main class".into()).into());
203        }
204        let mut destinations = std::collections::BTreeSet::new();
205        for download in &self.downloads {
206            if !destinations.insert(download.request.destination.clone()) {
207                return Err(
208                    LoaderError::DuplicatePath(download.request.destination.to_string()).into(),
209                );
210            }
211        }
212        for extraction in &self.archive_entries {
213            if extraction.entry.is_empty()
214                || extraction.entry.contains("..")
215                || extraction.entry.contains('\\')
216            {
217                return Err(LoaderError::InvalidPlan("unsafe archive entry".into()).into());
218            }
219        }
220        Ok(())
221    }
222}
223
224/// Public loader-version listing entry.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226pub struct LoaderVersion {
227    pub version: String,
228    pub stable: bool,
229}
230
231/// Services and base metadata available while resolving a loader plan.
232pub struct LoaderResolveContext<'a> {
233    pub downloads: &'a DownloadManager,
234    pub events: &'a EventBus,
235    pub cache_root: &'a std::path::Path,
236    pub base_version: Option<&'a VersionMetadata>,
237    pub cancellation: &'a CancellationToken,
238    pub offline: bool,
239}
240
241/// A loader implementation only interprets its own official metadata format.
242#[async_trait]
243pub trait Loader: Send + Sync {
244    fn kind(&self) -> LoaderKind;
245
246    async fn versions(
247        &self,
248        minecraft_version: &str,
249        context: &LoaderResolveContext<'_>,
250    ) -> Result<Vec<LoaderVersion>>;
251
252    async fn resolve(
253        &self,
254        config: &LoaderConfig,
255        minecraft_version: &str,
256        context: &LoaderResolveContext<'_>,
257    ) -> Result<LoaderPlan>;
258}
259
260/// Extensible dispatch table shared by every CentralCore pipeline.
261#[derive(Clone, Default)]
262pub struct LoaderRegistry {
263    implementations: Arc<BTreeMap<LoaderKind, Arc<dyn Loader>>>,
264}
265
266impl fmt::Debug for LoaderRegistry {
267    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
268        formatter
269            .debug_struct("LoaderRegistry")
270            .field("kinds", &self.implementations.keys().collect::<Vec<_>>())
271            .finish()
272    }
273}
274
275impl LoaderRegistry {
276    #[must_use]
277    pub fn with_defaults() -> Self {
278        let mut implementations = BTreeMap::<LoaderKind, Arc<dyn Loader>>::new();
279        implementations.insert(LoaderKind::Fabric, Arc::new(FabricLoader));
280        implementations.insert(LoaderKind::Forge, Arc::new(ForgeLoader));
281        Self {
282            implementations: Arc::new(implementations),
283        }
284    }
285
286    pub fn get(&self, kind: LoaderKind) -> Result<&Arc<dyn Loader>> {
287        self.implementations
288            .get(&kind)
289            .ok_or_else(|| LoaderError::UnsupportedKind(kind.to_string()).into())
290    }
291}
292
293/// Loader-facing facade exposed by [`crate::CentralCore`].
294#[derive(Debug, Clone)]
295pub struct LoaderManager {
296    registry: LoaderRegistry,
297    downloads: DownloadManager,
298    java: JavaManager,
299    events: EventBus,
300    cache_root: PathBuf,
301}
302
303impl LoaderManager {
304    pub(crate) fn new(
305        cache_root: PathBuf,
306        downloads: DownloadManager,
307        java: JavaManager,
308        events: EventBus,
309    ) -> Self {
310        Self {
311            registry: LoaderRegistry::with_defaults(),
312            downloads,
313            java,
314            events,
315            cache_root,
316        }
317    }
318
319    #[must_use]
320    pub fn registry(&self) -> &LoaderRegistry {
321        &self.registry
322    }
323
324    pub async fn versions(
325        &self,
326        kind: LoaderKind,
327        minecraft_version: &str,
328        cancellation: &CancellationToken,
329    ) -> Result<Vec<LoaderVersion>> {
330        self.events.emit(crate::CoreEvent::LoaderResolutionStarted {
331            loader: kind.to_string(),
332            minecraft_version: minecraft_version.to_owned(),
333            loader_version: None,
334        });
335        let context = LoaderResolveContext {
336            downloads: &self.downloads,
337            events: &self.events,
338            cache_root: &self.cache_root,
339            base_version: None,
340            cancellation,
341            offline: false,
342        };
343        let versions = self
344            .registry
345            .get(kind)?
346            .versions(minecraft_version, &context)
347            .await?;
348        self.events
349            .emit(crate::CoreEvent::LoaderResolutionCompleted {
350                loader: kind.to_string(),
351                minecraft_version: minecraft_version.to_owned(),
352                loader_version: versions
353                    .first()
354                    .map_or_else(String::new, |version| version.version.clone()),
355                downloads: 0,
356                processors: 0,
357            });
358        Ok(versions)
359    }
360
361    pub(crate) async fn resolve(
362        &self,
363        config: &LoaderConfig,
364        base_version: &VersionMetadata,
365        cancellation: &CancellationToken,
366        offline: bool,
367    ) -> Result<LoaderPlan> {
368        config.validate()?;
369        self.events.emit(crate::CoreEvent::LoaderResolutionStarted {
370            loader: config.kind.to_string(),
371            minecraft_version: base_version.id.clone(),
372            loader_version: Some(config.version.clone()),
373        });
374        let context = LoaderResolveContext {
375            downloads: &self.downloads,
376            events: &self.events,
377            cache_root: &self.cache_root,
378            base_version: Some(base_version),
379            cancellation,
380            offline,
381        };
382        let plan = self
383            .registry
384            .get(config.kind)?
385            .resolve(config, &base_version.id, &context)
386            .await?;
387        plan.validate()?;
388        self.events
389            .emit(crate::CoreEvent::LoaderResolutionCompleted {
390                loader: config.kind.to_string(),
391                minecraft_version: base_version.id.clone(),
392                loader_version: plan.identity.loader_version.clone(),
393                downloads: plan.downloads.len() as u64,
394                processors: plan.processors.len() as u64,
395            });
396        Ok(plan)
397    }
398
399    pub(crate) fn java(&self) -> &JavaManager {
400        &self.java
401    }
402}
403
404/// Structured loader-resolution and processor failures.
405#[derive(Debug, thiserror::Error)]
406#[non_exhaustive]
407pub enum LoaderError {
408    #[error("loader `{0}` is not available in this CentralCore build")]
409    UnsupportedKind(String),
410    #[error("loader version `{0}` is not an exact portable version")]
411    InvalidVersion(String),
412    #[error("{loader} {version} is not compatible with Minecraft {minecraft}")]
413    VersionNotFound {
414        loader: LoaderKind,
415        minecraft: String,
416        version: String,
417    },
418    #[error("invalid loader plan: {0}")]
419    InvalidPlan(String),
420    #[error("loader plan contains duplicate destination `{0}`")]
421    DuplicatePath(String),
422    #[error("unsupported Forge installer profile spec {0}")]
423    UnsupportedForgeSpec(u32),
424    #[error("loader metadata is invalid: {0}")]
425    InvalidMetadata(String),
426    #[error("loader processor `{id}` exited with code {code:?}")]
427    ProcessorFailed { id: String, code: Option<i32> },
428    #[error("loader processor `{id}` did not produce a valid `{path}`")]
429    InvalidProcessorOutput { id: String, path: String },
430    #[error("loader plan is unavailable in the local cache")]
431    OfflinePlanUnavailable,
432}
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437    use url::Url;
438
439    fn plan() -> LoaderPlan {
440        LoaderPlan {
441            format_version: LoaderPlan::FORMAT_VERSION,
442            identity: LoaderIdentity {
443                kind: LoaderKind::Fabric,
444                minecraft_version: "1.20.4".into(),
445                loader_version: "0.19.5".into(),
446            },
447            version_id: "fabric-loader-0.19.5-1.20.4".into(),
448            downloads: Vec::new(),
449            archive_entries: Vec::new(),
450            processors: Vec::new(),
451            classpath_additions: Vec::new(),
452            main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()),
453            jvm_arguments: vec![Argument::Plain("-Dcentralcore.loader=true".into())],
454            game_arguments: Vec::new(),
455            minimum_java_major: Some(17),
456        }
457    }
458
459    fn download(id: &str) -> LoaderDownload {
460        LoaderDownload {
461            request: DownloadRequest {
462                id: id.into(),
463                source: Url::parse("https://example.test/library.jar").expect("URL"),
464                destination: SafeRelativePath::new("libraries/example/library.jar").expect("path"),
465                expected_size: Some(4),
466                expected_hash: None,
467            },
468            kind: LoaderFileKind::Library,
469            classpath: true,
470        }
471    }
472
473    #[test]
474    fn plan_round_trips_as_versioned_data() {
475        let plan = plan();
476        plan.validate().expect("valid plan");
477        let json = serde_json::to_vec(&plan).expect("serialize");
478        let decoded: LoaderPlan = serde_json::from_slice(&json).expect("deserialize");
479        assert_eq!(decoded, plan);
480    }
481
482    #[test]
483    fn plan_rejects_duplicate_destinations() {
484        let mut plan = plan();
485        plan.downloads = vec![download("first"), download("second")];
486        assert!(matches!(
487            plan.validate(),
488            Err(Error::LoaderPlan(LoaderError::DuplicatePath(_)))
489        ));
490    }
491
492    #[test]
493    fn default_registry_contains_both_phase_five_loaders() {
494        let registry = LoaderRegistry::with_defaults();
495        assert!(registry.get(LoaderKind::Fabric).is_ok());
496        assert!(registry.get(LoaderKind::Forge).is_ok());
497        assert!(registry.get(LoaderKind::NeoForge).is_err());
498        assert!(registry.get(LoaderKind::Quilt).is_err());
499    }
500}