Skip to main content

dort_core/
batch.rs

1//! Selected-file batch planning.
2use crate::{
3    Error, Manifest, Result,
4    adoption::canonical,
5    context::HostContext,
6    journal,
7    model::ManagedFile,
8    planner::{self, Request as Single, UnmanageMode},
9};
10use serde::{Deserialize, Serialize};
11use std::path::Path;
12
13pub const MAX_FILES: usize = 32;
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum Action {
17    Adopt,
18    Apply,
19    Keep,
20    Remove,
21}
22#[derive(Clone)]
23pub enum Request {
24    Adopt(Vec<ManagedFile>),
25    Apply(Vec<String>),
26    Keep(Vec<String>),
27    Remove(Vec<String>),
28}
29impl Request {
30    pub fn action(&self) -> Action {
31        match self {
32            Self::Adopt(_) => Action::Adopt,
33            Self::Apply(_) => Action::Apply,
34            Self::Keep(_) => Action::Keep,
35            Self::Remove(_) => Action::Remove,
36        }
37    }
38}
39#[derive(Debug, Clone, Serialize)]
40pub struct Snapshot {
41    pub action: Action,
42    pub items: Vec<planner::Snapshot>,
43    pub blockers: Vec<String>,
44}
45#[derive(Debug, Clone, Serialize)]
46pub struct Plan {
47    pub schema: u32,
48    pub inputs: Snapshot,
49    pub items: Vec<planner::Plan>,
50    pub blockers: Vec<String>,
51}
52
53pub fn observe(
54    host: &HostContext,
55    repository: &Path,
56    profiles: &[String],
57    request: Request,
58) -> Result<Snapshot> {
59    let action = request.action();
60    let singles: Vec<_> = match request {
61        Request::Adopt(mappings) => mappings
62            .into_iter()
63            .map(|mapping| Single::Adopt { mapping })
64            .collect(),
65        Request::Apply(ids) | Request::Keep(ids) | Request::Remove(ids) => ids
66            .into_iter()
67            .map(|id| match action {
68                Action::Apply => Single::Unmanage {
69                    id,
70                    mode: UnmanageMode::Keep,
71                },
72                Action::Keep => Single::Unmanage {
73                    id,
74                    mode: UnmanageMode::Keep,
75                },
76                Action::Remove => Single::Unmanage {
77                    id,
78                    mode: UnmanageMode::Remove,
79                },
80                Action::Adopt => unreachable!(),
81            })
82            .collect(),
83    };
84    if singles.is_empty() || singles.len() > MAX_FILES {
85        return Err(Error::Invalid(
86            "batch requires 1–32 explicitly selected files".into(),
87        ));
88    }
89    let mut items = vec![];
90    for single in singles {
91        let mut observed = planner::observe(host, repository, profiles, single)?;
92        // Observe exactly the requested ID, not full-scope Apply. The pure per-file
93        // planner then computes Apply semantics on that explicitly observed snapshot.
94        if action == Action::Apply {
95            observed.request = Single::Apply;
96        }
97        items.push(observed);
98    }
99    items.sort_by(|a, b| a.files[0].mapping.id.cmp(&b.files[0].mapping.id));
100    let mut blockers = vec![];
101    if action == Action::Adopt {
102        let (mut manifest, entry) =
103            crate::observation::read_manifest(&repository.join("dort.toml"))?;
104        if items
105            .iter()
106            .any(|s| canonical(&s.manifest).ok() != canonical(&entry).ok())
107        {
108            return Err(Error::Invalid(
109                "manifest changed during batch observation".into(),
110            ));
111        }
112        let mappings: Vec<_> = items.iter().map(|s| s.files[0].mapping.clone()).collect();
113        validate_adoptions(&mut manifest, &mappings, host, profiles, repository)?;
114    }
115    if items.windows(2).any(|w| {
116        canonical(&w[0].manifest).ok() != canonical(&w[1].manifest).ok()
117            || canonical(&w[0].local_config).ok() != canonical(&w[1].local_config).ok()
118    }) {
119        blockers.push("configuration changed during batch observation".into());
120    }
121    Ok(Snapshot {
122        action,
123        items,
124        blockers,
125    })
126}
127
128pub(crate) fn validate_adoptions(
129    manifest: &mut Manifest,
130    mappings: &[ManagedFile],
131    host: &HostContext,
132    profiles: &[String],
133    repo: &Path,
134) -> Result<()> {
135    for mapping in mappings {
136        if !mapping.overrides.is_empty() {
137            return Err(Error::Invalid("batch adoption cannot add overrides".into()));
138        }
139        for existing in &manifest.files {
140            for source in std::iter::once(&existing.source).chain(existing.overrides.values()) {
141                if overlap(source, &mapping.source) {
142                    return Err(Error::Invalid("batch adoption sources overlap".into()));
143                }
144            }
145        }
146        manifest.files.push(mapping.clone());
147    }
148    let active = manifest.validate_for_host(host, profiles, Some(repo))?;
149    if mappings
150        .iter()
151        .any(|m| !crate::profiles::selected(&m.profiles, &active))
152    {
153        return Err(Error::Invalid(
154            "batch adoption mappings must all be active".into(),
155        ));
156    }
157    Ok(())
158}
159fn overlap(a: &Path, b: &Path) -> bool {
160    a.starts_with(b) || b.starts_with(a)
161}
162/// Pure deterministic combined planning, including cross-item identity/path conflicts.
163pub fn plan(inputs: Snapshot) -> Plan {
164    let mut blockers = inputs.blockers.clone();
165    if inputs.items.is_empty() || inputs.items.len() > MAX_FILES {
166        blockers.push("batch requires 1–32 files".into());
167    }
168    for (i, item) in inputs.items.iter().enumerate() {
169        let valid_request = matches!(
170            (inputs.action, &item.request),
171            (Action::Adopt, Single::Adopt { .. })
172                | (Action::Apply, Single::Apply)
173                | (
174                    Action::Keep,
175                    Single::Unmanage {
176                        mode: UnmanageMode::Keep,
177                        ..
178                    }
179                )
180                | (
181                    Action::Remove,
182                    Single::Unmanage {
183                        mode: UnmanageMode::Remove,
184                        ..
185                    }
186                )
187        );
188        if item.files.len() != 1 || !valid_request {
189            blockers.push("batch item scope mismatch".into());
190            continue;
191        }
192        for other in inputs.items.iter().take(i) {
193            if item.repository != other.repository
194                || journal::encode(&item.host).ok() != journal::encode(&other.host).ok()
195                || item.active_profiles != other.active_profiles
196                || canonical(&item.manifest).ok() != canonical(&other.manifest).ok()
197                || canonical(&item.local_config).ok() != canonical(&other.local_config).ok()
198            {
199                blockers
200                    .push("batch inputs must share one host, repository and configuration".into());
201            }
202            for a in &item.files {
203                for b in &other.files {
204                    if a.mapping.id == b.mapping.id
205                        || overlap(&a.target_path, &b.target_path)
206                        || overlap(&a.source_path, &b.source_path)
207                        || overlap(&a.source_path, &b.target_path)
208                        || overlap(&a.target_path, &b.source_path)
209                    {
210                        blockers.push("batch IDs, sources or destinations conflict".into());
211                    }
212                }
213            }
214        }
215    }
216    let items = inputs.items.iter().cloned().map(planner::plan).collect();
217    Plan {
218        schema: 4,
219        inputs,
220        items,
221        blockers,
222    }
223}
224impl Plan {
225    pub fn has_blockers(&self) -> bool {
226        !self.blockers.is_empty() || self.items.iter().any(planner::Plan::has_blockers)
227    }
228    pub fn human(&self) -> String {
229        let mut text = format!(
230            "Combined {:?} preview · {} selected files\nOne approval / one transaction; partial effects are possible on failure.\nFiltering and folding do not change this exact set.\n",
231            self.inputs.action,
232            self.items.len()
233        );
234        for b in &self.blockers {
235            text.push_str(&format!("BLOCKED: {b}\n"));
236        }
237        for item in &self.items {
238            text.push_str(&item.human());
239        }
240        text
241    }
242    pub(crate) fn request(&self) -> Request {
243        let mappings: Vec<_> = self
244            .inputs
245            .items
246            .iter()
247            .flat_map(|s| s.files.iter().map(|f| f.mapping.clone()))
248            .collect();
249        let ids = mappings.iter().map(|m| m.id.clone()).collect();
250        match self.inputs.action {
251            Action::Adopt => Request::Adopt(mappings),
252            Action::Apply => Request::Apply(ids),
253            Action::Keep => Request::Keep(ids),
254            Action::Remove => Request::Remove(ids),
255        }
256    }
257}
258/// One separately obtained exact-ID acknowledgement for every link to delete.
259pub struct RemovalAcknowledgements(Vec<String>);
260impl RemovalAcknowledgements {
261    pub fn confirm(ids: Vec<String>) -> Self {
262        Self(ids)
263    }
264}
265pub struct Approval {
266    pub(crate) plan: Plan,
267    pub(crate) digest: String,
268}
269impl Approval {
270    pub fn from_plan(plan: Plan) -> Result<Self> {
271        Self::approve(plan, None)
272    }
273    pub fn from_removal_plan(
274        plan: Plan,
275        acknowledgements: RemovalAcknowledgements,
276    ) -> Result<Self> {
277        Self::approve(plan, Some(acknowledgements))
278    }
279    fn approve(plan: Plan, ack: Option<RemovalAcknowledgements>) -> Result<Self> {
280        let mut expected: Vec<_> = plan
281            .inputs
282            .items
283            .iter()
284            .flat_map(|s| s.files.iter().map(|f| f.mapping.id.clone()))
285            .collect();
286        expected.sort();
287        let valid_ack = match (plan.inputs.action, ack) {
288            (Action::Remove, Some(mut ack)) => {
289                ack.0.sort();
290                ack.0 == expected
291            }
292            (Action::Remove, None) | (_, Some(_)) => false,
293            (_, None) => true,
294        };
295        if !valid_ack
296            || plan.has_blockers()
297            || canonical(&plan)? != canonical(&self::plan(plan.inputs.clone()))?
298        {
299            return Err(Error::Invalid("batch approval requires an unmodified unblocked combined plan and every removal ID separately acknowledged".into()));
300        }
301        let digest = journal::digest(canonical(&plan)?.as_bytes());
302        Ok(Self { plan, digest })
303    }
304    pub fn sha256(&self) -> &str {
305        &self.digest
306    }
307}
308pub use crate::batch_execution::{execute, rollback};