Skip to main content

elemental_addon/state/
modify.rs

1use elemental_driver::families::version_json::{
2    InstanceStorage, NamedMetadataPatch, PatchMode, PatchTrace, apply_metadata_patches_traced,
3    read_base_metadata,
4};
5use elemental_schema::mojang::piston::PistonMetaData;
6
7use crate::{
8    addon::{AddonPatchMode, InstalledAddon},
9    error::{Error, Result},
10};
11
12use super::{AddonState, load_addon_state, save_addon_state, sync_instance_patches};
13
14/// In-memory draft for modifying an instance's addon order and patch modes with zero-I/O
15/// [`PatchTrace`] previewing before committing changes to disk.
16#[derive(Debug, Clone)]
17pub struct AddonModify {
18    instance: InstanceStorage,
19    base: PistonMetaData,
20    original: AddonState,
21    draft: AddonState,
22    dirty: bool,
23}
24
25impl AddonModify {
26    /// Loads the clean metadata baseline and persisted addon state for `instance`.
27    pub async fn load(instance: InstanceStorage) -> Result<Self> {
28        let base = read_base_metadata(&instance)?;
29        let state = load_addon_state(&instance).await?;
30        Ok(Self {
31            instance,
32            base,
33            original: state.clone(),
34            draft: state,
35            dirty: false,
36        })
37    }
38
39    /// Returns the draft instance-wide [`PatchMode`] policy.
40    pub fn patch_mode(&self) -> PatchMode {
41        self.draft.patch_mode
42    }
43
44    /// Returns the current draft addon list with effective patch modes resolved.
45    pub fn addons(&self) -> Vec<InstalledAddon> {
46        self.draft
47            .addons
48            .iter()
49            .map(|record| record.to_installed(self.draft.patch_mode))
50            .collect()
51    }
52
53    /// Returns `true` when the draft has uncommitted modifications.
54    pub fn is_dirty(&self) -> bool {
55        self.dirty
56    }
57
58    /// Computes the current [`PatchTrace`] in memory without touching disk.
59    pub fn trace(&self) -> Result<PatchTrace> {
60        trace_state_with_extra(&self.base, &self.draft, &[])
61    }
62
63    /// Computes the [`PatchTrace`] in memory with additional ephemeral patches appended
64    /// (for example launch-scoped addons such as `authlib-injector`).
65    pub fn trace_with_extra(&self, extra_patches: &[NamedMetadataPatch]) -> Result<PatchTrace> {
66        trace_state_with_extra(&self.base, &self.draft, extra_patches)
67    }
68
69    /// Updates the preferred addon order in the draft and returns the resulting [`PatchTrace`].
70    ///
71    /// IDs listed in `ordered_ids` are placed first in that exact order; any remaining
72    /// installed addons retain their existing relative order afterwards.
73    pub fn reorder(&mut self, ordered_ids: &[&str]) -> Result<PatchTrace> {
74        for id in ordered_ids {
75            if !self.draft.addons.iter().any(|record| record.id == *id) {
76                return Err(Error::UnknownAddonInOrder {
77                    id: (*id).to_owned(),
78                });
79            }
80        }
81
82        let mut next = self.draft.clone();
83        let mut reordered = Vec::with_capacity(next.addons.len());
84        let mut remaining = std::mem::take(&mut next.addons);
85
86        for id in ordered_ids {
87            if let Some(pos) = remaining.iter().position(|record| record.id == *id) {
88                reordered.push(remaining.remove(pos));
89            }
90        }
91        reordered.extend(remaining);
92        next.addons = reordered;
93
94        let trace = trace_state_with_extra(&self.base, &next, &[])?;
95        self.draft = next;
96        self.dirty = true;
97        Ok(trace)
98    }
99
100    /// Updates the draft instance-wide [`PatchMode`] policy and returns the resulting [`PatchTrace`].
101    pub fn set_instance_patch_mode(&mut self, mode: PatchMode) -> Result<PatchTrace> {
102        let mut next = self.draft.clone();
103        next.patch_mode = mode;
104        next.validate_modes()?;
105        let trace = trace_state_with_extra(&self.base, &next, &[])?;
106        self.draft = next;
107        self.dirty = true;
108        Ok(trace)
109    }
110
111    /// Updates a single addon's [`AddonPatchMode`] preference in the draft and returns the resulting [`PatchTrace`].
112    pub fn set_addon_patch_mode(
113        &mut self,
114        addon_id: &str,
115        mode: AddonPatchMode,
116    ) -> Result<PatchTrace> {
117        let mut next = self.draft.clone();
118        let Some(record) = next.addons.iter_mut().find(|record| record.id == addon_id) else {
119            return Err(Error::AddonNotInstalled {
120                id: addon_id.to_owned(),
121            });
122        };
123        record.patch_mode = mode;
124        next.validate_modes()?;
125        let trace = trace_state_with_extra(&self.base, &next, &[])?;
126        self.draft = next;
127        self.dirty = true;
128        Ok(trace)
129    }
130
131    /// Discards all uncommitted draft changes and returns the restored [`PatchTrace`].
132    pub fn discard(&mut self) -> Result<PatchTrace> {
133        self.draft = self.original.clone();
134        self.dirty = false;
135        self.trace()
136    }
137
138    /// Persists the draft addon state and syncs physical/virtual metadata patches to disk.
139    pub async fn commit(&mut self) -> Result<PatchTrace> {
140        let trace = sync_instance_patches(&self.instance, &self.draft).await?;
141        save_addon_state(&self.instance, &self.draft).await?;
142        self.original = self.draft.clone();
143        self.dirty = false;
144        Ok(trace)
145    }
146}
147
148fn trace_state_with_extra(
149    base: &PistonMetaData,
150    state: &AddonState,
151    extra_patches: &[NamedMetadataPatch],
152) -> Result<PatchTrace> {
153    let mut patches = state.resolve_named_patches()?;
154    patches.extend(extra_patches.iter().cloned());
155    Ok(apply_metadata_patches_traced(base.clone(), &patches)?)
156}
157
158/// Reorders installed addons on `instance` and resyncs metadata patches.
159///
160/// IDs listed in `ordered_ids` are placed first in that exact order; any remaining
161/// installed addons retain their existing relative order afterwards.
162pub async fn reorder_instance_addons(
163    instance: &InstanceStorage,
164    ordered_ids: &[&str],
165) -> Result<PatchTrace> {
166    let mut modify = AddonModify::load(instance.clone()).await?;
167    modify.reorder(ordered_ids)?;
168    modify.commit().await
169}
170
171/// Switches an instance's [`PatchMode`] policy (`Virtual` <-> `Physical`) and resyncs metadata.
172pub async fn set_instance_patch_mode(
173    instance: &InstanceStorage,
174    mode: PatchMode,
175) -> Result<PatchTrace> {
176    let mut modify = AddonModify::load(instance.clone()).await?;
177    modify.set_instance_patch_mode(mode)?;
178    modify.commit().await
179}
180
181/// Updates an individual addon's [`AddonPatchMode`] preference and resyncs metadata.
182pub async fn set_addon_patch_mode(
183    instance: &InstanceStorage,
184    addon_id: &str,
185    mode: AddonPatchMode,
186) -> Result<PatchTrace> {
187    let mut modify = AddonModify::load(instance.clone()).await?;
188    modify.set_addon_patch_mode(addon_id, mode)?;
189    modify.commit().await
190}