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