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            if !crate::profiles::selected(
96                &observed.files[0].mapping.profiles,
97                &observed.active_profiles,
98            ) {
99                return Err(Error::Invalid(format!(
100                    "{}: file profile is off",
101                    observed.files[0].mapping.id
102                )));
103            }
104            observed.request = Single::Apply;
105        }
106        items.push(observed);
107    }
108    items.sort_by(|a, b| a.files[0].mapping.id.cmp(&b.files[0].mapping.id));
109    let mut blockers = vec![];
110    if action == Action::Adopt {
111        let (mut manifest, entry) =
112            crate::observation::read_manifest(&repository.join("dort.toml"))?;
113        if items
114            .iter()
115            .any(|s| canonical(&s.manifest).ok() != canonical(&entry).ok())
116        {
117            return Err(Error::Invalid(
118                "manifest changed during batch observation".into(),
119            ));
120        }
121        let mappings: Vec<_> = items.iter().map(|s| s.files[0].mapping.clone()).collect();
122        validate_adoptions(
123            &mut manifest,
124            &mappings,
125            host,
126            &items[0].active_profiles,
127            repository,
128        )?;
129    }
130    if items.windows(2).any(|w| {
131        canonical(&w[0].manifest).ok() != canonical(&w[1].manifest).ok()
132            || canonical(&w[0].local_config).ok() != canonical(&w[1].local_config).ok()
133    }) {
134        blockers.push("configuration changed during batch observation".into());
135    }
136    Ok(Snapshot {
137        action,
138        items,
139        blockers,
140    })
141}
142
143pub(crate) fn validate_adoptions(
144    manifest: &mut Manifest,
145    mappings: &[ManagedFile],
146    host: &HostContext,
147    active: &std::collections::BTreeSet<String>,
148    repo: &Path,
149) -> Result<()> {
150    for mapping in mappings {
151        if !mapping.overrides.is_empty() {
152            return Err(Error::Invalid("batch adoption cannot add overrides".into()));
153        }
154        for existing in &manifest.files {
155            for source in std::iter::once(&existing.source).chain(existing.overrides.values()) {
156                if overlap(source, &mapping.source) {
157                    return Err(Error::Invalid("batch adoption sources overlap".into()));
158                }
159            }
160        }
161        manifest.files.push(mapping.clone());
162    }
163    manifest.validate_selection(host, active, Some(repo))?;
164    if mappings
165        .iter()
166        .any(|m| !crate::profiles::selected(&m.profiles, active))
167    {
168        return Err(Error::Invalid(
169            "batch adoption mappings must all be active".into(),
170        ));
171    }
172    Ok(())
173}
174fn overlap(a: &Path, b: &Path) -> bool {
175    a.starts_with(b) || b.starts_with(a)
176}
177/// Pure deterministic combined planning, including cross-item identity/path conflicts.
178pub fn plan(inputs: Snapshot) -> Plan {
179    let mut blockers = inputs.blockers.clone();
180    if inputs.items.is_empty() || inputs.items.len() > MAX_FILES {
181        blockers.push("batch requires 1–32 files".into());
182    }
183    for (i, item) in inputs.items.iter().enumerate() {
184        let valid_request = matches!(
185            (inputs.action, &item.request),
186            (Action::Adopt, Single::Adopt { .. })
187                | (Action::Apply, Single::Apply)
188                | (
189                    Action::Keep,
190                    Single::Unmanage {
191                        mode: UnmanageMode::Keep,
192                        ..
193                    }
194                )
195                | (
196                    Action::Remove,
197                    Single::Unmanage {
198                        mode: UnmanageMode::Remove,
199                        ..
200                    }
201                )
202        );
203        if item.files.len() != 1 || !valid_request {
204            blockers.push("batch item scope mismatch".into());
205            continue;
206        }
207        for other in inputs.items.iter().take(i) {
208            if item.repository != other.repository
209                || journal::encode(&item.host).ok() != journal::encode(&other.host).ok()
210                || item.active_profiles != other.active_profiles
211                || canonical(&item.manifest).ok() != canonical(&other.manifest).ok()
212                || canonical(&item.local_config).ok() != canonical(&other.local_config).ok()
213            {
214                blockers
215                    .push("batch inputs must share one host, repository and configuration".into());
216            }
217            for a in &item.files {
218                for b in &other.files {
219                    if a.mapping.id == b.mapping.id
220                        || overlap(&a.target_path, &b.target_path)
221                        || overlap(&a.source_path, &b.source_path)
222                        || overlap(&a.source_path, &b.target_path)
223                        || overlap(&a.target_path, &b.source_path)
224                    {
225                        blockers.push("batch IDs, sources or destinations conflict".into());
226                    }
227                }
228            }
229        }
230    }
231    let items = inputs.items.iter().cloned().map(planner::plan).collect();
232    Plan {
233        schema: 4,
234        inputs,
235        items,
236        blockers,
237    }
238}
239impl Plan {
240    pub fn has_blockers(&self) -> bool {
241        !self.blockers.is_empty() || self.items.iter().any(planner::Plan::has_blockers)
242    }
243    pub fn human(&self) -> String {
244        let mut text = format!(
245            "Combined {:?} preview · {} selected files\nOne approval / one transaction; partial effects are possible on failure.\nFiltering and folding do not change this exact set.\n",
246            self.inputs.action,
247            self.items.len()
248        );
249        for b in &self.blockers {
250            text.push_str(&format!("BLOCKED: {b}\n"));
251        }
252        for item in &self.items {
253            text.push_str(&item.human());
254        }
255        text
256    }
257    pub(crate) fn request(&self) -> Request {
258        let mappings: Vec<_> = self
259            .inputs
260            .items
261            .iter()
262            .flat_map(|s| s.files.iter().map(|f| f.mapping.clone()))
263            .collect();
264        let ids = mappings.iter().map(|m| m.id.clone()).collect();
265        match self.inputs.action {
266            Action::Adopt => Request::Adopt(mappings),
267            Action::Apply => Request::Apply(ids),
268            Action::Keep => Request::Keep(ids),
269            Action::Remove => Request::Remove(ids),
270        }
271    }
272}
273/// One separately obtained exact-ID acknowledgement for every link to delete.
274pub struct RemovalAcknowledgements(Vec<String>);
275impl RemovalAcknowledgements {
276    pub fn confirm(ids: Vec<String>) -> Self {
277        Self(ids)
278    }
279}
280pub(crate) fn binding(plan: &Plan) -> Result<String> {
281    let mut stored = plan.clone();
282    for input in stored
283        .inputs
284        .items
285        .iter_mut()
286        .chain(stored.items.iter_mut().map(|p| &mut p.inputs))
287    {
288        input.profiles.clear();
289        input.temporary_profiles.clear();
290        input.inactive_links.clear();
291    }
292    Ok(journal::digest(canonical(&stored)?.as_bytes()))
293}
294
295pub struct Approval {
296    pub(crate) plan: Plan,
297    pub(crate) digest: String,
298}
299impl Approval {
300    pub fn from_plan(plan: Plan) -> Result<Self> {
301        Self::approve(plan, None)
302    }
303    pub fn from_removal_plan(
304        plan: Plan,
305        acknowledgements: RemovalAcknowledgements,
306    ) -> Result<Self> {
307        Self::approve(plan, Some(acknowledgements))
308    }
309    fn approve(plan: Plan, ack: Option<RemovalAcknowledgements>) -> Result<Self> {
310        let mut expected: Vec<_> = plan
311            .inputs
312            .items
313            .iter()
314            .flat_map(|s| s.files.iter().map(|f| f.mapping.id.clone()))
315            .collect();
316        expected.sort();
317        let valid_ack = match (plan.inputs.action, ack) {
318            (Action::Remove, Some(mut ack)) => {
319                ack.0.sort();
320                ack.0 == expected
321            }
322            (Action::Remove, None) | (_, Some(_)) => false,
323            (_, None) => true,
324        };
325        if !valid_ack
326            || plan.has_blockers()
327            || canonical(&plan)? != canonical(&self::plan(plan.inputs.clone()))?
328        {
329            return Err(Error::Invalid("batch approval requires an unmodified unblocked combined plan and every removal ID separately acknowledged".into()));
330        }
331        let digest = binding(&plan)?;
332        Ok(Self { plan, digest })
333    }
334    pub fn sha256(&self) -> &str {
335        &self.digest
336    }
337}
338pub use crate::batch_execution::{execute, rollback};