Skip to main content

artifactize_core/project/
selection.rs

1//! Project selectors, selection files, and profile variants.
2
3use std::{
4    collections::{BTreeMap, BTreeSet},
5    io::Read,
6    path::Path,
7};
8
9use serde::{Deserialize, Serialize};
10
11use crate::{
12    config::{ArtifactName, Eval, EvalId, RepoConfig},
13    graph::Graph,
14};
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
18pub enum Selection {
19    All,
20    Artifact {
21        #[serde(rename = "artifactId")]
22        artifact_id: ArtifactName,
23    },
24    Eval {
25        #[serde(rename = "evalId")]
26        eval_id: EvalId,
27    },
28    Artifacts {
29        #[serde(rename = "artifactIds")]
30        artifact_ids: Vec<ArtifactName>,
31    },
32    Evals {
33        #[serde(rename = "evalIds")]
34        eval_ids: Vec<EvalId>,
35    },
36}
37
38#[derive(Debug)]
39pub struct ResolvedSelection<'a> {
40    pub evals: Vec<&'a Eval>,
41    pub roots: Vec<&'a ArtifactName>,
42}
43
44impl Selection {
45    pub(crate) fn roots(&self) -> Option<Vec<ArtifactName>> {
46        let owner = |id: &EvalId| {
47            id.as_str()
48                .split_once('/')
49                .expect("qualified Eval")
50                .0
51                .parse()
52                .expect("validated Artifact name")
53        };
54        Some(match self {
55            Self::All => return None,
56            Self::Artifact { artifact_id } => vec![artifact_id.clone()],
57            Self::Artifacts { artifact_ids } => artifact_ids.clone(),
58            Self::Eval { eval_id } => vec![owner(eval_id)],
59            Self::Evals { eval_ids } => eval_ids.iter().map(owner).collect(),
60        })
61    }
62
63    /// Preserve selector order, then declaration order, keeping each root/Eval once. An
64    /// Artifact selector's roots are the Artifact and its parts.
65    pub fn resolve<'a>(&self, config: &'a RepoConfig) -> Result<ResolvedSelection<'a>, String> {
66        let evals_by_id: BTreeMap<_, _> = config
67            .evals
68            .iter()
69            .map(|eval| (eval.id.as_str(), eval))
70            .collect();
71        let mut evals_by_target: BTreeMap<&ArtifactName, Vec<&Eval>> = BTreeMap::new();
72        for eval in &config.evals {
73            evals_by_target.entry(&eval.target).or_default().push(eval);
74        }
75        let mut result = ResolvedSelection {
76            evals: Vec::new(),
77            roots: Vec::new(),
78        };
79        match self {
80            Self::All => {
81                result.evals.extend(&config.evals);
82                result.roots.extend(config.artifacts.keys());
83            }
84            Self::Artifact { artifact_id } => {
85                result.roots.push(selected_artifact(config, artifact_id)?);
86            }
87            Self::Artifacts { artifact_ids } => {
88                nonempty(artifact_ids)?;
89                for id in artifact_ids {
90                    result.roots.push(selected_artifact(config, id)?);
91                }
92            }
93            Self::Eval { eval_id } => {
94                result.evals.push(
95                    *evals_by_id
96                        .get(eval_id.as_str())
97                        .ok_or_else(|| format!("Unknown Eval: {eval_id}"))?,
98                );
99            }
100            Self::Evals { eval_ids } => {
101                nonempty(eval_ids)?;
102                for id in eval_ids {
103                    result.evals.push(
104                        *evals_by_id
105                            .get(id.as_str())
106                            .ok_or_else(|| format!("Unknown Eval: {id}"))?,
107                    );
108                }
109            }
110        }
111        if matches!(self, Self::Eval { .. } | Self::Evals { .. }) {
112            result
113                .roots
114                .extend(result.evals.iter().map(|eval| &eval.target));
115        }
116        // An Artifact is made of its parts, so selecting it selects them too.
117        if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
118            let parts: Vec<_> = result
119                .roots
120                .iter()
121                .flat_map(|&id| config.descendants(id))
122                .collect();
123            result.roots.extend(parts);
124        }
125        let mut seen = BTreeSet::new();
126        result.roots.retain(|id| seen.insert(*id));
127        if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
128            result.evals.extend(
129                result
130                    .roots
131                    .iter()
132                    .filter_map(|id| evals_by_target.get(id))
133                    .flatten(),
134            );
135        }
136        let mut seen_evals = BTreeSet::new();
137        result
138            .evals
139            .retain(|eval| seen_evals.insert(eval.id.as_str()));
140        Ok(result)
141    }
142
143    /// Recursive execution includes every Eval in the required Artifact scope. An Artifact
144    /// selection also includes its cycle peers' Evals, after the selected ones: they review
145    /// the selected Artifact, so only this Run can give them current results.
146    pub fn included_evals<'a>(
147        &self,
148        config: &'a RepoConfig,
149        recursive: bool,
150    ) -> Result<Vec<&'a Eval>, String> {
151        if !recursive && !matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
152            return Ok(self.resolve(config)?.evals);
153        }
154        let graph = Graph::new(config).map_err(|error| error.to_string())?;
155        Ok(self.plan(config, &graph, recursive)?.included)
156    }
157
158    pub(crate) fn plan<'a>(
159        &self,
160        config: &'a RepoConfig,
161        graph: &Graph<'a>,
162        recursive: bool,
163    ) -> Result<Plan<'a>, String> {
164        let selected = self.resolve(config)?;
165        let required: BTreeSet<_> = graph
166            .dependency_closure(&selected.roots)
167            .map_err(|error| error.to_string())?
168            .into_iter()
169            .collect();
170        let evals: Vec<_> = config
171            .evals
172            .iter()
173            .filter(|eval| required.contains(&eval.target))
174            .collect();
175        let included = if recursive {
176            evals.clone()
177        } else if matches!(self, Self::Artifact { .. } | Self::Artifacts { .. }) {
178            let peers: BTreeSet<_> = graph
179                .cycle_members(&selected.roots)
180                .map_err(|error| error.to_string())?
181                .into_iter()
182                .collect();
183            let selected_ids: BTreeSet<_> = selected.evals.iter().map(|eval| &eval.id).collect();
184            selected
185                .evals
186                .iter()
187                .copied()
188                .chain(evals.iter().copied().filter(|eval| {
189                    peers.contains(&eval.target) && !selected_ids.contains(&eval.id)
190                }))
191                .collect()
192        } else {
193            selected.evals.clone()
194        };
195        Ok(Plan {
196            selected: selected.evals,
197            included,
198            required,
199            evals,
200        })
201    }
202}
203
204/// A Run and a status forecast use the same execution selection and evidence scope.
205pub(crate) struct Plan<'a> {
206    pub selected: Vec<&'a Eval>,
207    pub included: Vec<&'a Eval>,
208    pub required: BTreeSet<&'a ArtifactName>,
209    pub evals: Vec<&'a Eval>,
210}
211
212fn nonempty<T>(ids: &[T]) -> Result<(), String> {
213    if ids.is_empty() {
214        return Err("Multi-root selection requires a nonempty array of IDs.".into());
215    }
216    Ok(())
217}
218
219fn selected_artifact<'a>(config: &'a RepoConfig, id: &str) -> Result<&'a ArtifactName, String> {
220    config
221        .artifacts
222        .get_key_value(id)
223        .map(|(id, _)| id)
224        .ok_or_else(|| format!("Unknown Artifact: {id}"))
225}
226
227/// Bound selection-file parsing/allocation before resolving any project work.
228const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
229/// Bound resolution and deduplication work even for files containing many short IDs.
230const MAX_IDS: usize = 100_000;
231const FILE_FORMAT_ERROR: &str =
232    "Selection file must contain 1–100000 nonempty IDs, as a JSON string array or one ID per line.";
233
234// Match ECMAScript trim, including BOM but excluding NEXT LINE.
235fn trim(text: &str) -> &str {
236    text.trim_matches(|ch| {
237        matches!(ch,
238            '\u{0009}'..='\u{000d}' | '\u{0020}' | '\u{00a0}' | '\u{1680}' |
239            '\u{2000}'..='\u{200a}' | '\u{2028}' | '\u{2029}' | '\u{202f}' |
240            '\u{205f}' | '\u{3000}' | '\u{feff}'
241        )
242    })
243}
244
245pub fn parse_selection_file(text: &str) -> Result<Vec<String>, String> {
246    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
247    if text.len() > MAX_FILE_BYTES {
248        return Err("Selection file exceeds 4 MiB.".into());
249    }
250    let ids: Vec<String> = if trim(text).starts_with('[') {
251        serde_json::from_str::<Vec<String>>(text).map_err(|error| {
252            // A valid array containing a non-string is a format error, not broken JSON.
253            // Validate only syntax after a data error, preserving malformed-array precedence.
254            if error.is_data() && serde_json::from_str::<crate::json::Ignored>(text).is_ok() {
255                FILE_FORMAT_ERROR.to_owned()
256            } else {
257                "Selection file contains invalid JSON.".to_owned()
258            }
259        })?
260    } else {
261        text.split('\n')
262            .map(trim)
263            .filter(|line| !line.is_empty())
264            .take(MAX_IDS + 1)
265            .map(str::to_owned)
266            .collect()
267    };
268    if ids.is_empty()
269        || ids.len() > MAX_IDS
270        || ids.iter().any(|id| {
271            id.is_empty()
272                || trim(id) != id
273                || id
274                    .bytes()
275                    .any(|byte| byte <= b' ' || byte == 127 || byte == b',')
276        })
277    {
278        return Err(FILE_FORMAT_ERROR.into());
279    }
280    let mut seen = BTreeSet::new();
281    Ok(ids
282        .into_iter()
283        .filter(|id| seen.insert(id.clone()))
284        .collect())
285}
286
287pub fn read_selection_file(path: &Path) -> Result<Vec<String>, String> {
288    // Nonblocking open lets us reject a FIFO without waiting for its writer.
289    let file = crate::platform::open_nonblocking(path)
290        .map_err(|error| format!("{}: {error}", crate::platform::path_text(path)))?;
291    let info = file.metadata().map_err(|error| error.to_string())?;
292    if !info.is_file() || info.len() > MAX_FILE_BYTES as u64 {
293        return Err("Selection input must be a regular file no larger than 4 MiB.".into());
294    }
295    let mut bytes = Vec::new();
296    file.take(MAX_FILE_BYTES as u64 + 1)
297        .read_to_end(&mut bytes)
298        .map_err(|error| error.to_string())?;
299    if bytes.len() > MAX_FILE_BYTES {
300        return Err("Selection file exceeds 4 MiB.".into());
301    }
302    parse_selection_file(&String::from_utf8_lossy(&bytes))
303}
304
305#[cfg(test)]
306mod tests;