1use std::collections::BTreeMap;
11use std::fmt::Write as _;
12use std::io;
13use std::path::{Component, Path, PathBuf};
14use std::time::SystemTime;
15
16use ignore::WalkBuilder;
17use sha2::{Digest, Sha256};
18
19#[cfg(test)]
20mod tests;
21
22pub const IGNORE_FILE: &str = ".schedrignore";
24
25pub const SKIPPED_DIRS: [&str; 2] = [".git", "__pycache__"];
27
28pub const HASH_PREFIX: &str = "sha256:";
30
31#[derive(Debug, thiserror::Error)]
33pub enum ScanError {
34 #[error("can't read DAG root {}: {source}", root.display())]
36 Root {
37 root: PathBuf,
39 source: io::Error,
41 },
42 #[error("scanning DAG root {}: {source}", root.display())]
44 Walk {
45 root: PathBuf,
47 source: ignore::Error,
49 },
50 #[error("{}: the path isn't valid UTF-8", path.display())]
52 NotUtf8 {
53 path: PathBuf,
55 },
56 #[error("reading {}: {source}", path.display())]
58 Read {
59 path: PathBuf,
61 source: io::Error,
63 },
64 #[error("copying DAG code to {}: {source}", path.display())]
66 Copy {
67 path: PathBuf,
69 source: io::Error,
71 },
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Stamp {
77 pub len: u64,
79 pub modified: Option<SystemTime>,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Snapshot {
87 root: PathBuf,
88 files: BTreeMap<String, Stamp>,
89}
90
91impl Snapshot {
92 #[must_use]
94 pub fn root(&self) -> &Path {
95 &self.root
96 }
97
98 #[must_use]
100 pub const fn files(&self) -> &BTreeMap<String, Stamp> {
101 &self.files
102 }
103
104 #[must_use]
106 pub fn python_files(&self) -> Vec<String> {
107 self.files
108 .keys()
109 .filter(|path| Path::new(path).extension().is_some_and(|ext| ext == "py"))
110 .cloned()
111 .collect()
112 }
113}
114
115pub const DAG_FILE_MARK: &[u8] = b"schedr";
117
118#[must_use]
123pub fn mentions_schedr(path: &Path) -> bool {
124 use std::io::Read as _;
125 if !path.metadata().is_ok_and(|found| found.is_file()) {
126 return true;
127 }
128 let Ok(mut file) = std::fs::File::open(path) else {
129 return true;
130 };
131 let mut buffer = vec![0; 64 * 1024];
132 let mut kept = 0;
134 loop {
135 match file.read(&mut buffer[kept..]) {
136 Ok(0) => return false,
137 Ok(read) => {
138 let filled = kept + read;
139 if buffer[..filled]
140 .windows(DAG_FILE_MARK.len())
141 .any(|window| window == DAG_FILE_MARK)
142 {
143 return true;
144 }
145 kept = filled.min(DAG_FILE_MARK.len() - 1);
146 buffer.copy_within(filled - kept..filled, 0);
147 }
148 Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
149 Err(_) => return true,
150 }
151 }
152}
153
154#[must_use]
157pub fn split_dag_files(dir: &Path, files: Vec<String>) -> (Vec<String>, Vec<String>) {
158 files
159 .into_iter()
160 .partition(|file| mentions_schedr(&dir.join(file)))
161}
162
163pub fn scan(root: &Path) -> Result<Snapshot, ScanError> {
170 let resolved = root.canonicalize().map_err(|source| ScanError::Root {
171 root: root.to_owned(),
172 source,
173 })?;
174 let mut walk = WalkBuilder::new(&resolved);
175 walk.standard_filters(false)
176 .follow_links(true)
177 .add_custom_ignore_filename(IGNORE_FILE)
178 .filter_entry(|entry| {
179 let is_dir = entry.file_type().is_some_and(|t| t.is_dir());
180 let name = entry.file_name().to_string_lossy();
181 let skipped_dir = is_dir && SKIPPED_DIRS.contains(&name.as_ref());
182 let bytecode = Path::new(name.as_ref())
183 .extension()
184 .is_some_and(|ext| ext == "pyc");
185 !skipped_dir && !bytecode
186 });
187 let mut files = BTreeMap::new();
188 for entry in walk.build() {
189 let entry = entry.map_err(|source| ScanError::Walk {
190 root: resolved.clone(),
191 source,
192 })?;
193 if !entry.file_type().is_some_and(|t| t.is_file()) {
194 continue;
195 }
196 let metadata = entry.metadata().map_err(|source| ScanError::Walk {
197 root: resolved.clone(),
198 source,
199 })?;
200 let relative = relative_path(&resolved, entry.path())?;
201 let stamp = Stamp {
202 len: metadata.len(),
203 modified: metadata.modified().ok(),
204 };
205 files.insert(relative, stamp);
206 }
207 Ok(Snapshot {
208 root: resolved,
209 files,
210 })
211}
212
213pub fn content_hash(snapshot: &Snapshot) -> Result<String, ScanError> {
221 let mut hasher = Sha256::new();
222 for path in snapshot.files.keys() {
223 let full = snapshot.root.join(path);
224 hash_file(&mut hasher, path, &full)
225 .map_err(|source| ScanError::Read { path: full, source })?;
226 }
227 Ok(hex_hash(hasher))
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
232pub struct Captured {
233 pub hash: String,
235 pub dir: PathBuf,
237 pub fresh: bool,
239}
240
241pub fn capture(snapshot: &Snapshot, store: &Path) -> Result<Captured, ScanError> {
258 use std::os::unix::fs::PermissionsExt;
259 let copy_error = |path: &Path| {
260 let path = path.to_path_buf();
261 move |source| ScanError::Copy { path, source }
262 };
263 let hash = content_hash(snapshot)?;
264 let dir = store.join(hash.replace(':', "-"));
265 if dir.is_dir() {
266 return Ok(Captured {
268 hash,
269 dir,
270 fresh: false,
271 });
272 }
273 std::fs::create_dir_all(store).map_err(copy_error(store))?;
274 let partial = Partial::new(store).map_err(copy_error(store))?;
275 let mut hasher = Sha256::new();
276 for path in snapshot.files.keys() {
277 let full = snapshot.root.join(path);
278 let read_error = |source| ScanError::Read {
279 path: full.clone(),
280 source,
281 };
282 let mut source = std::fs::File::open(&full).map_err(read_error)?;
283 let mode = source.metadata().map_err(read_error)?.permissions().mode();
284 let target = partial.path().join(path);
285 if let Some(parent) = target.parent() {
286 std::fs::create_dir_all(parent).map_err(copy_error(parent))?;
287 }
288 let mut copy = std::fs::File::create(&target).map_err(copy_error(&target))?;
291 let mut buffer = vec![0; COPY_BUFFER];
292 loop {
293 let read = io::Read::read(&mut source, &mut buffer).map_err(read_error)?;
294 if read == 0 {
295 break;
296 }
297 io::Write::write_all(&mut copy, &buffer[..read]).map_err(copy_error(&target))?;
298 }
299 drop(copy);
300 std::fs::set_permissions(&target, std::fs::Permissions::from_mode(mode & 0o555))
301 .map_err(copy_error(&target))?;
302 hash_file(&mut hasher, path, &target).map_err(copy_error(&target))?;
304 }
305 let hash = hex_hash(hasher);
307 let dir = store.join(hash.replace(':', "-"));
308 if dir.is_dir() {
309 return Ok(Captured {
310 hash,
311 dir,
312 fresh: false,
313 });
314 }
315 set_dirs_read_only(partial.path()).map_err(copy_error(partial.path()))?;
316 std::fs::set_permissions(partial.path(), std::fs::Permissions::from_mode(0o755))
319 .map_err(copy_error(partial.path()))?;
320 std::fs::rename(partial.path(), &dir).map_err(copy_error(&dir))?;
321 partial.kept();
322 std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555))
323 .map_err(copy_error(&dir))?;
324 Ok(Captured {
325 hash,
326 dir,
327 fresh: true,
328 })
329}
330
331fn temporary(store: &Path, kind: &str) -> PathBuf {
334 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
335 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
336 store.join(format!(".{kind}-{}-{n}", std::process::id()))
337}
338
339struct Partial(Option<PathBuf>);
342
343impl Partial {
344 fn new(store: &Path) -> io::Result<Self> {
345 let path = temporary(store, "capture");
346 std::fs::create_dir(&path)?;
347 Ok(Self(Some(path)))
348 }
349
350 fn path(&self) -> &Path {
351 self.0.as_deref().unwrap_or(Path::new(""))
352 }
353
354 fn kept(mut self) {
356 self.0 = None;
357 }
358}
359
360impl Drop for Partial {
361 fn drop(&mut self) {
362 if let Some(path) = &self.0 {
363 let _ = remove_capture(path);
364 }
365 }
366}
367
368fn set_dirs_read_only(dir: &Path) -> io::Result<()> {
370 use std::os::unix::fs::PermissionsExt;
371 for entry in std::fs::read_dir(dir)? {
372 let entry = entry?;
373 if entry.file_type()?.is_dir() {
374 set_dirs_read_only(&entry.path())?;
375 }
376 }
377 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o555))
378}
379
380pub fn remove_tree(dir: &Path) -> io::Result<()> {
386 use std::os::unix::fs::PermissionsExt;
387 fn writable(dir: &Path) -> io::Result<()> {
388 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
389 for entry in std::fs::read_dir(dir)? {
390 let entry = entry?;
391 if entry.file_type()?.is_dir() {
392 writable(&entry.path())?;
393 }
394 }
395 Ok(())
396 }
397 writable(dir)?;
398 std::fs::remove_dir_all(dir)
399}
400
401pub fn remove_capture(dir: &Path) -> io::Result<()> {
409 use std::os::unix::fs::PermissionsExt;
410 fn writable(dir: &Path) -> io::Result<()> {
411 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
412 for entry in std::fs::read_dir(dir)? {
413 let entry = entry?;
414 if entry.file_type()?.is_dir() {
415 writable(&entry.path())?;
416 }
417 }
418 Ok(())
419 }
420 let temporary_already = dir
421 .file_name()
422 .is_some_and(|name| name.to_string_lossy().starts_with('.'));
423 let doomed = match dir.parent() {
424 Some(store) if !temporary_already => {
425 let doomed = temporary(store, "removing");
426 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?;
428 std::fs::rename(dir, &doomed)?;
429 doomed
430 }
431 _ => dir.to_path_buf(),
432 };
433 writable(&doomed)?;
434 std::fs::remove_dir_all(&doomed)
435}
436
437const COPY_BUFFER: usize = 64 << 10;
440
441fn hash_file(hasher: &mut Sha256, path: &str, full: &Path) -> io::Result<()> {
445 let mut file = std::fs::File::open(full)?;
446 let size = file.metadata()?.len();
447 hasher.update(path.as_bytes());
448 hasher.update([0]);
449 hasher.update(size.to_be_bytes());
450 let mut buffer = vec![0; COPY_BUFFER];
451 let mut read_total = 0;
452 loop {
453 let read = io::Read::read(&mut file, &mut buffer)?;
454 if read == 0 {
455 break;
456 }
457 read_total += read as u64;
458 if read_total > size {
459 break;
460 }
461 hasher.update(&buffer[..read]);
462 }
463 if read_total != size {
464 return Err(io::Error::other(format!(
465 "its size changed while it was read ({size} bytes, then {read_total})"
466 )));
467 }
468 Ok(())
469}
470
471fn hex_hash(hasher: Sha256) -> String {
473 let digest = hasher.finalize();
474 let mut hash = String::from(HASH_PREFIX);
475 for byte in digest {
476 let _ = write!(hash, "{byte:02x}");
477 }
478 hash
479}
480
481fn relative_path(root: &Path, path: &Path) -> Result<String, ScanError> {
482 let relative = path.strip_prefix(root).unwrap_or(path);
483 let mut parts = Vec::new();
484 for component in relative.components() {
485 if let Component::Normal(part) = component {
486 let part = part.to_str().ok_or_else(|| ScanError::NotUtf8 {
487 path: path.to_owned(),
488 })?;
489 parts.push(part);
490 }
491 }
492 Ok(parts.join("/"))
493}