publish.rs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //! Portable publication of derived files into a shared cache directory.
  2. //!
  3. //! Several copies of the runner can prepare the same title at once. Each
  4. //! writer stages into its own file, so two of them cannot truncate each
  5. //! other's bytes or rename a file the other already published. The final
  6. //! rename is atomic within the directory, and the staging file is removed
  7. //! if publication fails.
  8. use std::path::Path;
  9. use std::sync::atomic::{AtomicU64, Ordering};
  10. static NEXT_STAGING: AtomicU64 = AtomicU64::new(0);
  11. /// Writes `bytes` to `path` unless it is already there, using a staging file
  12. /// unique to this process and call.
  13. pub fn write_if_changed(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
  14. if std::fs::read(path).is_ok_and(|existing| existing == bytes) {
  15. return Ok(());
  16. }
  17. let name = path
  18. .file_name()
  19. .and_then(|name| name.to_str())
  20. .unwrap_or("image");
  21. let sequence = NEXT_STAGING.fetch_add(1, Ordering::Relaxed);
  22. let staging = path.with_file_name(format!(
  23. ".{name}.{}.{sequence}.tmp",
  24. std::process::id()
  25. ));
  26. std::fs::write(&staging, bytes)?;
  27. if let Err(error) = std::fs::rename(&staging, path) {
  28. let _ = std::fs::remove_file(&staging);
  29. return Err(error);
  30. }
  31. Ok(())
  32. }
  33. #[cfg(test)]
  34. mod tests {
  35. use super::*;
  36. /// Two publishers staging the same destination at once both succeed,
  37. /// and neither leaves a staging file behind.
  38. #[test]
  39. fn concurrent_publishers_do_not_share_a_staging_file() {
  40. let dir = tempfile::tempdir().unwrap();
  41. let path = dir.path().join("image.bin");
  42. let bytes = b"a prepared image".to_vec();
  43. let (first, second) = (path.clone(), path.clone());
  44. let (first_bytes, second_bytes) = (bytes.clone(), bytes.clone());
  45. let (one, two) = (
  46. std::thread::spawn(move || write_if_changed(&first, &first_bytes)),
  47. std::thread::spawn(move || write_if_changed(&second, &second_bytes)),
  48. );
  49. one.join().unwrap().unwrap();
  50. two.join().unwrap().unwrap();
  51. assert_eq!(std::fs::read(&path).unwrap(), bytes);
  52. let leftovers: Vec<_> = std::fs::read_dir(dir.path())
  53. .unwrap()
  54. .filter_map(|entry| entry.ok())
  55. .filter(|entry| entry.path() != path)
  56. .collect();
  57. assert!(leftovers.is_empty(), "staging files were removed: {leftovers:?}");
  58. }
  59. #[test]
  60. fn a_failed_publication_removes_its_staging_file() {
  61. let dir = tempfile::tempdir().unwrap();
  62. let path = dir.path().join("missing-parent").join("image.bin");
  63. assert!(write_if_changed(&path, b"bytes").is_err());
  64. let leftovers: Vec<_> = std::fs::read_dir(dir.path())
  65. .unwrap()
  66. .filter_map(|entry| entry.ok())
  67. .collect();
  68. assert!(leftovers.is_empty(), "no staging file survives an error");
  69. }
  70. }