1use super::{IgnorePatterns, content, dependencies, eval_key, scratch};
4use crate::{
5 config::{ArtifactName, Eval, Fingerprint, RepoConfig},
6 process, runtime, scope, workspace,
7};
8use futures_util::{StreamExt, stream::FuturesUnordered};
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use std::{
12 collections::{BTreeMap, BTreeSet},
13 path::Path,
14 sync::Arc,
15};
16use tokio::sync::Semaphore;
17use tokio_util::sync::CancellationToken;
18
19const MANIFEST_BYTES: usize = 64 * 1024;
22
23const FINGERPRINT_INPUT_VERSION: u32 = 1;
26const MANIFEST_DIGEST_PREFIX_BYTES: usize = 8;
29
30#[derive(Debug, Clone)]
32pub struct PreparedFingerprint {
33 pub value: crate::types::Fingerprint,
34 pub manifest: Option<Manifest>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Manifest {
41 pub inputs: crate::types::Sha256Digest,
43 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub files: Option<BTreeMap<scope::LogicalTarget, crate::types::DigestPrefix>>,
46}
47
48#[derive(Debug, Clone)]
51pub struct Parallelism {
52 slots: Arc<Semaphore>,
53 limit: usize,
54}
55
56impl Parallelism {
57 pub fn new(limit: usize) -> Result<Self, String> {
59 let limit = limit.max(1);
60 if limit > Semaphore::MAX_PERMITS {
61 return Err(format!(
62 "fingerprint jobs must be at most {}.",
63 Semaphore::MAX_PERMITS
64 ));
65 }
66 Ok(Self {
67 slots: Arc::new(Semaphore::new(limit)),
68 limit,
69 })
70 }
71
72 pub fn available() -> usize {
74 std::thread::available_parallelism().map_or(1, usize::from)
75 }
76
77 pub fn limit(&self) -> usize {
78 self.limit
79 }
80}
81
82pub(crate) fn validate_file_inputs(config: &RepoConfig, eval: &Eval) -> Result<(), String> {
84 for id in dependencies(config, eval) {
85 scope::validate_file_target(&config.root, &config.artifacts[id])
86 .map_err(|error| error.to_string())?;
87 }
88 Ok(())
89}
90
91pub async fn prepare<'a>(
96 config: &RepoConfig,
97 artifacts: impl IntoIterator<Item = &'a ArtifactName>,
98 output_root: &Path,
99 parallelism: &Parallelism,
100 cancellation: CancellationToken,
101) -> Result<BTreeMap<&'a ArtifactName, PreparedFingerprint>, String> {
102 let artifacts = artifacts.into_iter().collect::<Vec<_>>();
103 for id in &artifacts {
104 let artifact = config
105 .artifacts
106 .get(*id)
107 .ok_or_else(|| format!("Unknown Artifact: {id}"))?;
108 scope::validate_file_target(&config.root, artifact).map_err(|error| error.to_string())?;
109 }
110 let mut prepared = BTreeMap::new();
111 prepare_each(
112 config,
113 artifacts,
114 output_root,
115 parallelism,
116 cancellation,
117 |id, fingerprint| {
118 prepared.insert(id, fingerprint);
119 },
120 )
121 .await?;
122 Ok(prepared)
123}
124
125pub(crate) async fn prepare_each<'a>(
127 config: &RepoConfig,
128 artifacts: impl IntoIterator<Item = &'a ArtifactName>,
129 output_root: &Path,
130 parallelism: &Parallelism,
131 cancellation: CancellationToken,
132 mut ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
133) -> Result<(), String> {
134 let artifacts: Vec<_> = artifacts
137 .into_iter()
138 .filter(|id| scope::validate_file_target(&config.root, &config.artifacts[*id]).is_ok())
139 .collect();
140 let mut seen = BTreeSet::new();
141 let ids: Vec<&'a ArtifactName> = artifacts
142 .into_iter()
143 .filter(|id| config.artifacts[*id].fingerprint.is_some() && seen.insert(*id))
144 .collect();
145 let tokens: Vec<_> = ids.iter().map(|_| cancellation.child_token()).collect();
146 let mut running: FuturesUnordered<_> = ids
147 .iter()
148 .zip(&tokens)
149 .enumerate()
150 .map(|(index, (id, token))| async move {
151 let result = match parallelism.slots.acquire().await {
152 Ok(_slot) if !token.is_cancelled() => {
154 compute(config, id, output_root, token.clone()).await
155 }
156 _ => Err(process::Error::Cancelled.to_string()),
157 };
158 (index, result)
159 })
160 .collect();
161 let mut failure: Option<(usize, String)> = None;
162 while let Some((index, result)) = running.next().await {
163 match result {
164 Ok(fingerprint) => ready(ids[index], fingerprint),
165 Err(error) if failure.as_ref().is_none_or(|(first, _)| index < *first) => {
166 for token in &tokens[index + 1..] {
167 token.cancel();
168 }
169 failure = Some((index, error));
170 }
171 Err(_) => {}
172 }
173 }
174 match failure {
175 Some((_, error)) => Err(error),
176 None => Ok(()),
177 }
178}
179
180pub async fn recheck(
183 config: &RepoConfig,
184 eval: &Eval,
185 output_root: &Path,
186 parallelism: &Parallelism,
187 cancellation: CancellationToken,
188) -> Result<Option<crate::types::ReuseKey>, String> {
189 validate_file_inputs(config, eval)?;
190 let fingerprints = prepare(
191 config,
192 dependencies(config, eval),
193 output_root,
194 parallelism,
195 cancellation,
196 )
197 .await?;
198 validate_file_inputs(config, eval)?;
199 Ok(eval_key(config, eval, &fingerprints)
200 .ok()
201 .map(|key| key.value))
202}
203
204pub(crate) async fn recheck_observations(
206 config: &RepoConfig,
207 expected: &BTreeMap<ArtifactName, crate::types::Fingerprint>,
208 output: &Path,
209 parallelism: &Parallelism,
210 cancellation: CancellationToken,
211) -> Result<bool, String> {
212 let current = prepare(config, expected.keys(), output, parallelism, cancellation).await?;
213 Ok(expected.iter().all(|(name, value)| {
214 current
215 .get(name)
216 .is_some_and(|current| current.value == *value)
217 }))
218}
219
220async fn compute(
221 config: &RepoConfig,
222 id: &ArtifactName,
223 output_root: &Path,
224 cancellation: CancellationToken,
225) -> Result<PreparedFingerprint, String> {
226 scope::validate_file_target(&config.root, &config.artifacts[id])
227 .map_err(|error| error.to_string())?;
228 let result = match &config.artifacts[id].fingerprint {
229 Some(Fingerprint::Graph) => Ok(PreparedFingerprint {
231 value: crate::graph_structure::read_scoped(&config.root, &config.artifacts[id])?
232 .fingerprint(),
233 manifest: None,
234 }),
235 Some(Fingerprint::Artifactsum { files, ignore }) => {
236 content(config, id, files, ignore, &cancellation)
237 .await
238 .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
239 }
240 Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
241 value: script(config, id, output_root, cancellation)
242 .await
243 .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
244 manifest: None,
245 }),
246 None => Err(format!("Artifact {id} declares fingerprint: false.")),
247 }?;
248 scope::validate_file_target(&config.root, &config.artifacts[id])
249 .map_err(|error| error.to_string())?;
250 Ok(result)
251}
252
253async fn content(
255 config: &RepoConfig,
256 id: &ArtifactName,
257 inputs: &[crate::config::LogicalPath],
258 ignore: &IgnorePatterns,
259 cancellation: &CancellationToken,
260) -> Result<PreparedFingerprint, String> {
261 let files = content::files(config, id, inputs, ignore, cancellation).await?;
262 Ok(artifactsum(files))
263}
264
265fn artifactsum(files: content::Files) -> PreparedFingerprint {
266 let mut manifest = Manifest {
267 inputs: files.digest.clone(),
268 files: Some(
269 files
270 .files
271 .iter()
272 .map(|(path, file)| {
273 (
274 path.clone(),
275 content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
276 .parse()
277 .expect("eight-byte SHA-256 prefix"),
278 )
279 })
280 .collect(),
281 ),
282 };
283 if serde_json::to_vec(&manifest)
284 .expect("manifest is JSON")
285 .len()
286 > MANIFEST_BYTES
287 {
288 manifest.files = None;
289 }
290 PreparedFingerprint {
291 value: format!("artifactsum:{}", files.digest)
292 .parse()
293 .expect("artifactsum digest is a fingerprint"),
294 manifest: Some(manifest),
295 }
296}
297
298async fn script(
299 config: &RepoConfig,
300 artifact_id: &ArtifactName,
301 output_root: &Path,
302 cancellation: CancellationToken,
303) -> Result<crate::types::Fingerprint, String> {
304 if cancellation.is_cancelled() {
305 return Err(process::Error::Cancelled.to_string());
306 }
307 let artifact = &config.artifacts[artifact_id];
308 let Some(Fingerprint::Script {
309 command,
310 args,
311 files,
312 timeout_ms,
313 }) = &artifact.fingerprint
314 else {
315 unreachable!("fingerprint script")
316 };
317 let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
318 for input in files {
319 scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
320 }
321 let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
322 let program = scope::executable(&config.root, &scope, artifact_id, command)
323 .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
324 let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
325 let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id});
326 let output_root =
327 workspace::prepare_directory(output_root, &config.root).map_err(|e| e.to_string())?;
328 let disposable = scratch::Scratch::create(&output_root).map_err(|e| e.to_string())?;
329 let result = async {
330 let mut command = runtime::Command::prepare(
331 program,
332 args.iter().map(Into::into).collect(),
333 &config.root,
334 disposable.path(),
335 *timeout_ms,
336 )
337 .map_err(|e| e.to_string())?;
338 command.cwd = cwd;
339 let output = command
340 .output(input.to_string().into_bytes(), cancellation.clone())
341 .await
342 .map_err(|e| e.to_string())?;
343 if !output.status.success() {
344 return Err(format!(
345 "Fingerprint command exited with {}.",
346 output.status
347 ));
348 }
349 if output.truncated {
350 return Err("Fingerprint command output exceeded its limit.".into());
351 }
352 validate_output(&output.stdout)
353 }
354 .await;
355 let cleaned = disposable.close();
356 if cancellation.is_cancelled() {
357 return Err(process::Error::Cancelled.to_string());
358 }
359 let value = result?;
360 cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
361 Ok(value)
362}
363
364fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
365 let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
366 if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
367 || !value
368 .iter()
369 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
370 {
371 return Err(format!(
372 "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
373 ));
374 }
375 String::from_utf8(value.to_vec())
376 .map_err(|error| error.to_string())?
377 .parse()
378}