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 {
230 value: crate::graph_structure::read(&config.root)?.fingerprint(),
231 manifest: None,
232 }),
233 Some(Fingerprint::Artifactsum { files, ignore }) => {
234 content(config, id, files, ignore, &cancellation)
235 .await
236 .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
237 }
238 Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
239 value: script(config, id, output_root, cancellation)
240 .await
241 .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
242 manifest: None,
243 }),
244 None => Err(format!("Artifact {id} declares fingerprint: false.")),
245 }?;
246 scope::validate_file_target(&config.root, &config.artifacts[id])
247 .map_err(|error| error.to_string())?;
248 Ok(result)
249}
250
251async fn content(
253 config: &RepoConfig,
254 id: &ArtifactName,
255 inputs: &[crate::config::LogicalPath],
256 ignore: &IgnorePatterns,
257 cancellation: &CancellationToken,
258) -> Result<PreparedFingerprint, String> {
259 let files = content::files(config, id, inputs, ignore, cancellation).await?;
260 Ok(artifactsum(files))
261}
262
263fn artifactsum(files: content::Files) -> PreparedFingerprint {
264 let mut manifest = Manifest {
265 inputs: files.digest.clone(),
266 files: Some(
267 files
268 .files
269 .iter()
270 .map(|(path, file)| {
271 (
272 path.clone(),
273 content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
274 .parse()
275 .expect("eight-byte SHA-256 prefix"),
276 )
277 })
278 .collect(),
279 ),
280 };
281 if serde_json::to_vec(&manifest)
282 .expect("manifest is JSON")
283 .len()
284 > MANIFEST_BYTES
285 {
286 manifest.files = None;
287 }
288 PreparedFingerprint {
289 value: format!("artifactsum:{}", files.digest)
290 .parse()
291 .expect("artifactsum digest is a fingerprint"),
292 manifest: Some(manifest),
293 }
294}
295
296async fn script(
297 config: &RepoConfig,
298 artifact_id: &ArtifactName,
299 output_root: &Path,
300 cancellation: CancellationToken,
301) -> Result<crate::types::Fingerprint, String> {
302 if cancellation.is_cancelled() {
303 return Err(process::Error::Cancelled.to_string());
304 }
305 let artifact = &config.artifacts[artifact_id];
306 let Some(Fingerprint::Script {
307 command,
308 args,
309 files,
310 timeout_ms,
311 }) = &artifact.fingerprint
312 else {
313 unreachable!("fingerprint script")
314 };
315 let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
316 for input in files {
317 scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
318 }
319 let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
320 let program = scope::executable(&config.root, &scope, artifact_id, command)
321 .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
322 let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
323 let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id});
324 let output_root =
325 workspace::prepare_directory(output_root, &config.root).map_err(|e| e.to_string())?;
326 let disposable = scratch::Scratch::create(&output_root).map_err(|e| e.to_string())?;
327 let result = async {
328 let mut command = runtime::Command::prepare(
329 program,
330 args.iter().map(Into::into).collect(),
331 &config.root,
332 disposable.path(),
333 *timeout_ms,
334 )
335 .map_err(|e| e.to_string())?;
336 command.cwd = cwd;
337 let output = command
338 .output(input.to_string().into_bytes(), cancellation.clone())
339 .await
340 .map_err(|e| e.to_string())?;
341 if !output.status.success() {
342 return Err(format!(
343 "Fingerprint command exited with {}.",
344 output.status
345 ));
346 }
347 if output.truncated {
348 return Err("Fingerprint command output exceeded its limit.".into());
349 }
350 validate_output(&output.stdout)
351 }
352 .await;
353 let cleaned = disposable.close();
354 if cancellation.is_cancelled() {
355 return Err(process::Error::Cancelled.to_string());
356 }
357 let value = result?;
358 cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
359 Ok(value)
360}
361
362fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
363 let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
364 if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
365 || !value
366 .iter()
367 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
368 {
369 return Err(format!(
370 "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
371 ));
372 }
373 String::from_utf8(value.to_vec())
374 .map_err(|error| error.to_string())?
375 .parse()
376}