Skip to main content

elemental_addon/
addon.rs

1use std::{borrow::Cow, path::PathBuf, sync::Arc};
2
3use async_trait::async_trait;
4use elemental_core::{
5    auth::credential::Credential, minecraft::MinecraftVersionId, runtime::RuntimeResolver,
6};
7use elemental_driver::{
8    catalog::GameVersion,
9    driver::{DriverDescriptor, InstanceProbe},
10    families::version_json::{InstanceStorage, MetadataPatch, PatchMode},
11    launch::RuntimeOptions,
12};
13use elemental_infra::downloader::DownloadSession;
14use serde::{Deserialize, Serialize};
15
16use crate::error::{Error, Result};
17
18/// Identifies an addon type by stable machine ID and human-readable display name.
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub struct AddonDescriptor {
21    /// Stable machine-readable identifier (for example, `"liteloader"`).
22    pub id: Cow<'static, str>,
23    /// Human-readable display name.
24    pub name: Cow<'static, str>,
25}
26
27impl AddonDescriptor {
28    /// Creates a new addon descriptor from a machine ID and display name.
29    pub fn new(id: impl Into<Cow<'static, str>>, name: impl Into<Cow<'static, str>>) -> Self {
30        Self {
31            id: id.into(),
32            name: name.into(),
33        }
34    }
35}
36
37/// Which patch modes an [`Addon`] is capable of supporting.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum PatchModeSupport {
41    /// Only supports launch-time virtual overlays (`vpatch`) and/or runtime hooks.
42    VirtualOnly,
43    /// Requires physical writes into the instance's `version.json`.
44    PhysicalOnly,
45    /// Supports both virtual overlays (`vpatch`) and physical `version.json` patching.
46    #[default]
47    Both,
48}
49
50/// Per-addon patch mode preference, monotonically constrained by the instance-level [`PatchMode`].
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
52#[serde(rename_all = "lowercase")]
53pub enum AddonPatchMode {
54    /// Follow the instance's [`PatchMode`] policy (default).
55    #[default]
56    Inherit,
57    /// Force virtual patching (`vpatch`) regardless of a `Physical` instance policy.
58    Virtual,
59    /// Request physical patching into `version.json` (rejected if instance policy is `Virtual`).
60    Physical,
61}
62
63/// Resolves the effective [`PatchMode`] for an addon given the instance-level policy,
64/// the addon's per-addon preference, and the addon's declared capability.
65///
66/// Enforces monotonic tightening: an addon can tighten a `Physical` instance policy down
67/// to `Virtual`, but can never elevate a `Virtual` instance policy to `Physical`.
68pub fn resolve_effective_patch_mode(
69    addon_id: &str,
70    instance_policy: PatchMode,
71    addon_mode: AddonPatchMode,
72    support: PatchModeSupport,
73) -> Result<PatchMode> {
74    if instance_policy == PatchMode::Virtual
75        && (addon_mode == AddonPatchMode::Physical || support == PatchModeSupport::PhysicalOnly)
76    {
77        return Err(Error::PatchModeDisallowedByInstance {
78            id: addon_id.to_owned(),
79            instance_policy,
80        });
81    }
82
83    match (addon_mode, support) {
84        (AddonPatchMode::Physical, PatchModeSupport::VirtualOnly) => {
85            Err(Error::PatchModeUnsupported {
86                id: addon_id.to_owned(),
87                requested: PatchMode::Physical,
88                supported: "VirtualOnly".to_owned(),
89            })
90        }
91        (AddonPatchMode::Virtual, PatchModeSupport::PhysicalOnly) => {
92            Err(Error::PatchModeUnsupported {
93                id: addon_id.to_owned(),
94                requested: PatchMode::Virtual,
95                supported: "PhysicalOnly".to_owned(),
96            })
97        }
98        (AddonPatchMode::Virtual, _) => Ok(PatchMode::Virtual),
99        (AddonPatchMode::Physical, _) => Ok(PatchMode::Physical),
100        (AddonPatchMode::Inherit, PatchModeSupport::VirtualOnly) => Ok(PatchMode::Virtual),
101        (AddonPatchMode::Inherit, PatchModeSupport::PhysicalOnly) => Ok(PatchMode::Physical),
102        (AddonPatchMode::Inherit, PatchModeSupport::Both) => Ok(instance_policy),
103    }
104}
105
106/// Whether an installed addon is managed by Elemental or detected from an external launcher.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
108#[serde(rename_all = "lowercase")]
109pub enum AddonOrigin {
110    /// Installed and tracked by Elemental in `.elemental/addons.json`.
111    Elemental,
112    /// Detected from an existing instance's metadata or files without an Elemental state record.
113    External,
114}
115
116/// Result of checking whether an addon can be applied to a host driver and game version.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum AddonCompatibility {
119    /// The addon can be applied to the target host instance.
120    Compatible,
121    /// The addon cannot be applied to the target host instance.
122    Incompatible {
123        /// Human-readable explanation of why the addon is incompatible.
124        reason: String,
125    },
126}
127
128/// Read-only context passed to [`Addon::check_compatibility`].
129pub struct AddonContext<'a> {
130    /// Host driver installed on the target instance.
131    pub driver: DriverDescriptor,
132    /// Target Minecraft version, when known.
133    pub game_version: Option<&'a MinecraftVersionId>,
134    /// Storage handle for the target instance directory.
135    pub instance: &'a InstanceStorage,
136}
137
138/// Inputs passed to [`Addon::prepare`].
139pub struct AddonPrepareRequest<'a> {
140    /// Active download session used to download addon artifacts.
141    pub session: &'a DownloadSession,
142    /// Storage handle for the target instance directory.
143    pub instance: &'a InstanceStorage,
144    /// Host driver installed on the target instance.
145    pub driver: DriverDescriptor,
146    /// Minecraft version of the target instance.
147    pub game_version: &'a MinecraftVersionId,
148    /// Requested addon version, if specified by the caller.
149    pub addon_version: Option<&'a str>,
150    /// Runtime options configured for installation/launch preparation.
151    pub runtime_options: &'a RuntimeOptions,
152    /// Runtime resolver for locating Java installations when needed.
153    pub runtime_resolver: &'a RuntimeResolver,
154}
155
156/// Output produced by [`Addon::prepare`].
157#[derive(Debug, Clone, Default)]
158pub struct AddonPrepareOutput {
159    /// Resolved addon version string to persist in instance state.
160    pub version: Option<String>,
161    /// Declarative metadata patch layered onto the instance's `PistonMetaData`.
162    pub metadata_patch: Option<MetadataPatch>,
163    /// Additional files created/managed by this addon (tracked for cleanup on removal).
164    pub managed_files: Vec<PathBuf>,
165}
166
167/// Launch-time argument injections produced by [`Addon::augment_launch`].
168#[derive(Debug, Clone, Default, PartialEq, Eq)]
169pub struct AddonLaunchArgs {
170    /// Additional JVM flags appended before the main class.
171    pub extra_jvm_arguments: Vec<String>,
172    /// Additional game arguments appended after the host driver's game arguments.
173    pub extra_game_arguments: Vec<String>,
174}
175
176/// Context passed to [`Addon::augment_launch`].
177pub struct AddonLaunchContext<'a> {
178    /// Storage handle for the instance being launched.
179    pub instance: &'a InstanceStorage,
180    /// Host driver of the instance being launched.
181    pub driver: DriverDescriptor,
182    /// Authenticated player credential for this launch.
183    pub credential: &'a Credential,
184    /// Persisted state record for this addon on the instance.
185    pub record: &'a InstalledAddonRecord,
186}
187
188/// Summary of an addon installed or detected on an instance.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190pub struct InstalledAddon {
191    /// Machine-readable addon identifier.
192    pub id: String,
193    /// Human-readable addon display name.
194    pub name: String,
195    /// Installed addon version, when known.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub version: Option<String>,
198    /// Whether this addon is Elemental-managed or externally detected.
199    pub origin: AddonOrigin,
200    /// Effective patch mode resolved from instance policy and per-addon preference.
201    #[serde(default)]
202    pub effective_patch_mode: PatchMode,
203    /// Whether launching requires executing [`Addon::augment_launch`] in code.
204    #[serde(default)]
205    pub requires_runtime_hook: bool,
206}
207
208/// Persisted state record for a single addon installed on an instance.
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct InstalledAddonRecord {
211    /// Machine-readable addon identifier.
212    pub id: String,
213    /// Human-readable addon display name.
214    pub name: String,
215    /// Installed addon version, when recorded.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub version: Option<String>,
218    /// Origin indicating whether Elemental or an external launcher installed the addon.
219    pub origin: AddonOrigin,
220    /// Per-addon patch mode preference.
221    #[serde(default)]
222    pub patch_mode: AddonPatchMode,
223    /// Patch mode capabilities declared by the addon when installed.
224    #[serde(default)]
225    pub patch_mode_support: PatchModeSupport,
226    /// Whether this addon requires a launch-time hook via [`Addon::augment_launch`].
227    #[serde(default)]
228    pub requires_runtime_hook: bool,
229    /// Instance-relative paths of files managed by this addon.
230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231    pub managed_files: Vec<String>,
232    /// Stored metadata patch applied in [`PatchMode::Virtual`] or [`PatchMode::Physical`].
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub metadata_patch: Option<MetadataPatch>,
235}
236
237impl InstalledAddonRecord {
238    /// Computes the effective [`PatchMode`] constrained by `instance_policy`.
239    pub fn effective_patch_mode(&self, instance_policy: PatchMode) -> Result<PatchMode> {
240        resolve_effective_patch_mode(
241            &self.id,
242            instance_policy,
243            self.patch_mode,
244            self.patch_mode_support,
245        )
246    }
247
248    /// Converts this persisted record into a public [`InstalledAddon`] summary.
249    pub fn to_installed(&self, instance_policy: PatchMode) -> InstalledAddon {
250        let effective_patch_mode = self
251            .effective_patch_mode(instance_policy)
252            .unwrap_or(PatchMode::Virtual);
253        InstalledAddon {
254            id: self.id.clone(),
255            name: self.name.clone(),
256            version: self.version.clone(),
257            origin: self.origin,
258            effective_patch_mode,
259            requires_runtime_hook: self.requires_runtime_hook,
260        }
261    }
262}
263
264/// A catalog entry describing an available version of an [`Addon`].
265#[derive(Clone, Debug, PartialEq, Eq, Hash)]
266pub struct AddonRelease {
267    /// Addon release version string.
268    pub version: String,
269    /// Optional release channel (for example, `"release"` or `"snapshot"`).
270    pub channel: Option<String>,
271    /// Optional publication timestamp string from the upstream source.
272    pub published_at: Option<String>,
273    /// Whether the upstream catalog marks this release as a prerelease.
274    pub prerelease: Option<bool>,
275}
276
277impl AddonRelease {
278    /// Creates a release entry for the given addon `version`.
279    pub fn new(version: impl Into<String>) -> Self {
280        Self {
281            version: version.into(),
282            channel: None,
283            published_at: None,
284            prerelease: None,
285        }
286    }
287
288    /// Sets the release channel label.
289    pub fn with_channel(mut self, channel: Option<String>) -> Self {
290        self.channel = channel;
291        self
292    }
293
294    /// Sets the publication timestamp string.
295    pub fn with_published_at(mut self, published_at: Option<String>) -> Self {
296        self.published_at = published_at;
297        self
298    }
299
300    /// Sets whether this release is a prerelease.
301    pub fn with_prerelease(mut self, prerelease: Option<bool>) -> Self {
302        self.prerelease = prerelease;
303        self
304    }
305}
306
307/// Optional host driver and game version filters for querying an addon's version catalog.
308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
309pub struct AddonCatalogQuery<'a> {
310    /// Optional host driver filter to query compatible addon releases for.
311    pub driver: Option<DriverDescriptor>,
312    /// Optional Minecraft version filter to query compatible addon releases for.
313    pub game_version: Option<&'a MinecraftVersionId>,
314}
315
316impl<'a> AddonCatalogQuery<'a> {
317    /// Creates an unfiltered catalog query.
318    pub fn new() -> Self {
319        Self::default()
320    }
321
322    /// Filters releases by host `driver`.
323    pub fn with_driver(mut self, driver: DriverDescriptor) -> Self {
324        self.driver = Some(driver);
325        self
326    }
327
328    /// Filters releases by Minecraft `game_version`.
329    pub fn with_game_version(mut self, game_version: &'a MinecraftVersionId) -> Self {
330        self.game_version = Some(game_version);
331        self
332    }
333}
334
335/// Composable, host-aware extension layered onto a Minecraft instance.
336#[async_trait]
337pub trait Addon: Send + Sync {
338    /// Returns the addon's unique identifier and display name.
339    fn descriptor(&self) -> AddonDescriptor;
340
341    /// Declares which patch modes this addon supports.
342    fn patch_mode_support(&self) -> PatchModeSupport {
343        PatchModeSupport::Both
344    }
345
346    /// Returns `true` when this addon requires code execution during launch
347    /// command construction (`augment_launch`) and cannot degrade to data-only.
348    fn requires_runtime_hook(&self) -> bool {
349        false
350    }
351
352    /// Returns supported game versions when this addon exposes a remote catalog.
353    async fn supported_game_versions(&self) -> Result<Option<Vec<GameVersion>>> {
354        Ok(None)
355    }
356
357    /// Returns available addon releases for a host driver and game version, or
358    /// `None` when this addon does not provide a version catalog.
359    async fn available_versions(
360        &self,
361        _query: &AddonCatalogQuery<'_>,
362    ) -> Result<Option<Vec<AddonRelease>>> {
363        Ok(None)
364    }
365
366    /// Checks whether this addon is compatible with the host driver and game version.
367    fn check_compatibility(&self, _ctx: &AddonContext<'_>) -> AddonCompatibility {
368        AddonCompatibility::Compatible
369    }
370
371    /// Detects whether an unmanaged/external copy of this addon is already present in `probe`.
372    async fn inspect(&self, _probe: &InstanceProbe) -> Result<Option<InstalledAddon>> {
373        Ok(None)
374    }
375
376    /// Downloads any required artifacts and produces the metadata patch and managed files
377    /// to persist for this addon.
378    async fn prepare(&self, _request: &AddonPrepareRequest<'_>) -> Result<AddonPrepareOutput> {
379        Ok(AddonPrepareOutput::default())
380    }
381
382    /// Augments the launch command with dynamic JVM or game arguments before spawning.
383    async fn augment_launch(
384        &self,
385        _args: &mut AddonLaunchArgs,
386        _ctx: &AddonLaunchContext<'_>,
387    ) -> Result<()> {
388        Ok(())
389    }
390}
391
392#[async_trait]
393impl<T: Addon + ?Sized> Addon for Arc<T> {
394    fn descriptor(&self) -> AddonDescriptor {
395        (**self).descriptor()
396    }
397
398    fn patch_mode_support(&self) -> PatchModeSupport {
399        (**self).patch_mode_support()
400    }
401
402    fn requires_runtime_hook(&self) -> bool {
403        (**self).requires_runtime_hook()
404    }
405
406    async fn supported_game_versions(&self) -> Result<Option<Vec<GameVersion>>> {
407        (**self).supported_game_versions().await
408    }
409
410    async fn available_versions(
411        &self,
412        query: &AddonCatalogQuery<'_>,
413    ) -> Result<Option<Vec<AddonRelease>>> {
414        (**self).available_versions(query).await
415    }
416
417    fn check_compatibility(&self, ctx: &AddonContext<'_>) -> AddonCompatibility {
418        (**self).check_compatibility(ctx)
419    }
420
421    async fn inspect(&self, probe: &InstanceProbe) -> Result<Option<InstalledAddon>> {
422        (**self).inspect(probe).await
423    }
424
425    async fn prepare(&self, request: &AddonPrepareRequest<'_>) -> Result<AddonPrepareOutput> {
426        (**self).prepare(request).await
427    }
428
429    async fn augment_launch(
430        &self,
431        args: &mut AddonLaunchArgs,
432        ctx: &AddonLaunchContext<'_>,
433    ) -> Result<()> {
434        (**self).augment_launch(args, ctx).await
435    }
436}