centralcore 1.0.2

Open-source Rust library for building Minecraft Java Edition launchers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Generic mod-loader planning, registry, execution, and persistence.

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;

/// Loader families understood by the public model.
#[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()),
        }
    }
}

/// Versioned loader selection attached to an instance.
#[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)
    }

    /// Validates a portable, exact loader version coordinate.
    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(())
    }
}

/// Reproducible identity embedded in every loader plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderIdentity {
    pub kind: LoaderKind,
    pub minecraft_version: String,
    pub loader_version: String,
}

/// Role of a loader-owned object in the managed-file index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoaderFileKind {
    Metadata,
    Library,
    Installer,
    Processor,
    Generated,
}

/// One cache download produced by a loader resolver.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderDownload {
    pub request: DownloadRequest,
    pub kind: LoaderFileKind,
    #[serde(default)]
    pub classpath: bool,
}

/// Exact archive member copied to a controlled cache-relative destination.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchiveEntryPlan {
    pub archive: SafeRelativePath,
    pub entry: String,
    pub destination: SafeRelativePath,
    pub expected_hash: Option<FileHash>,
}

/// A processor argument already normalized by its loader implementation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum ProcessorArgument {
    Literal(String),
    CacheRoot,
    CachePath(SafeRelativePath),
}

/// A file generated by a trusted loader processor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessorOutput {
    pub path: SafeRelativePath,
    pub expected_size: Option<u64>,
    pub expected_hash: Option<FileHash>,
}

/// One ordered Java operation emitted by an official loader implementation.
#[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>,
}

/// Generic, serializable overlay composed with a Vanilla installation.
#[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(())
    }
}

/// Public loader-version listing entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderVersion {
    pub version: String,
    pub stable: bool,
}

/// Services and base metadata available while resolving a loader plan.
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,
}

/// A loader implementation only interprets its own official metadata format.
#[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>;
}

/// Extensible dispatch table shared by every CentralCore pipeline.
#[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())
    }
}

/// Loader-facing facade exposed by [`crate::CentralCore`].
#[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
    }
}

/// Structured loader-resolution and processor failures.
#[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());
    }
}