1use std::fs::File;
9use std::io;
10use std::path::{Path, PathBuf};
11use std::time::{Duration, Instant};
12
13mod lifetime;
14mod memory;
15mod os_version;
16#[cfg(unix)]
17mod unix;
18#[cfg(unix)]
19use unix as platform;
20#[cfg(windows)]
21mod windows;
22#[cfg(windows)]
23use windows as platform;
24
25pub use lifetime::{
26 KillOnCloseJob, claim_stdout, exit_without_handlers, stop_std_handle_inheritance, watch_parent,
27};
28#[cfg(any(target_os = "linux", target_os = "android"))]
29pub use memory::{
30 CgroupMemory, CgroupMemoryWatch, cgroup_memory, cgroup_memory_at, memory_capacity_at,
31};
32pub use memory::{MemoryCapacity, memory_capacity};
33pub use os_version::os_version;
34
35pub fn try_lock_exclusive(file: &File) -> io::Result<bool> {
53 platform::try_lock_exclusive(file)
54}
55
56pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
63 platform::same_file(file, path)
64}
65
66pub fn same_file_at(a: &Path, b: &Path) -> io::Result<bool> {
72 platform::same_file_at(a, b)
73}
74
75#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub enum PublishMethod {
78 RenameNoReplace,
82 PlaceholderRename,
85 RenameReplace,
87}
88
89impl PublishMethod {
90 #[must_use]
92 pub const fn as_str(self) -> &'static str {
93 match self {
94 Self::RenameNoReplace => "rename-no-replace",
95 Self::PlaceholderRename => "placeholder-rename",
96 Self::RenameReplace => "rename-replace",
97 }
98 }
99}
100
101#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub struct Published {
104 pub method: PublishMethod,
106 pub retries: u32,
108}
109
110#[derive(Clone, Copy)]
112pub struct RetryPolicy<'a> {
113 pub budget: Duration,
115 pub on_wait: &'a dyn Fn() -> bool,
117}
118
119fn keep_waiting() -> bool {
120 true
121}
122
123impl RetryPolicy<'static> {
124 pub const NONE: Self = Self {
126 budget: Duration::ZERO,
127 on_wait: &keep_waiting,
128 };
129}
130
131impl std::fmt::Debug for RetryPolicy<'_> {
132 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 formatter
134 .debug_struct("RetryPolicy")
135 .field("budget", &self.budget)
136 .finish_non_exhaustive()
137 }
138}
139
140const RETRY_FIRST_DELAY: Duration = Duration::from_millis(50);
142const RETRY_MAX_DELAY: Duration = Duration::from_secs(1);
143
144pub fn with_publish_retries<T>(
150 retry: &RetryPolicy<'_>,
151 step: impl FnMut() -> io::Result<T>,
152) -> io::Result<(T, u32)> {
153 retrying(retry, is_retryable_publish_error, step)
154}
155
156fn retrying<T>(
157 retry: &RetryPolicy<'_>,
158 retryable: impl Fn(&io::Error) -> bool,
159 mut step: impl FnMut() -> io::Result<T>,
160) -> io::Result<(T, u32)> {
161 let started = Instant::now();
162 let mut delay = RETRY_FIRST_DELAY;
163 let mut retries = 0_u32;
164 loop {
165 match step() {
166 Ok(value) => return Ok((value, retries)),
167 Err(error) => {
168 let elapsed = started.elapsed();
169 if !retryable(&error) || elapsed >= retry.budget || !(retry.on_wait)() {
170 return Err(error);
171 }
172 std::thread::sleep(delay.min(retry.budget.saturating_sub(elapsed)));
173 retries = retries.saturating_add(1);
174 delay = (delay * 2).min(RETRY_MAX_DELAY);
175 }
176 }
177 }
178}
179
180#[must_use]
188pub fn is_retryable_publish_error(error: &io::Error) -> bool {
189 platform::is_retryable_publish_error(error)
190}
191
192pub fn publish_no_replace(
206 from: &Path,
207 to: &Path,
208 retry: &RetryPolicy<'_>,
209) -> io::Result<Published> {
210 publish_no_replace_with(from, to, retry, &platform::rename_exclusive)
211}
212
213fn publish_no_replace_with(
215 from: &Path,
216 to: &Path,
217 retry: &RetryPolicy<'_>,
218 rename_exclusive: &dyn Fn(&Path, &Path) -> io::Result<()>,
219) -> io::Result<Published> {
220 let (method, retries) = with_publish_retries(retry, || match rename_exclusive(from, to) {
221 Ok(()) => Ok(PublishMethod::RenameNoReplace),
222 Err(error) if platform::flag_refused(&error) => {
223 publish_through_placeholder(from, to).map(|()| PublishMethod::PlaceholderRename)
224 }
225 Err(error) => Err(error),
226 })?;
227 Ok(Published { method, retries })
228}
229
230fn publish_through_placeholder(from: &Path, to: &Path) -> io::Result<()> {
236 let placeholder = std::fs::OpenOptions::new()
237 .write(true)
238 .create_new(true)
239 .open(to)?;
240 let identity = platform::file_identity(&placeholder);
241 drop(placeholder);
242 let renamed = std::fs::rename(from, to);
243 if renamed.is_err()
244 && let Ok(identity) = identity
245 && platform::path_identity(to).ok().flatten() == Some(identity)
246 {
247 let _ = std::fs::remove_file(to);
248 }
249 renamed
250}
251
252pub fn publish_replace(from: &Path, to: &Path, retry: &RetryPolicy<'_>) -> io::Result<Published> {
258 let ((), retries) = with_publish_retries(retry, || std::fs::rename(from, to))?;
259 Ok(Published {
260 method: PublishMethod::RenameReplace,
261 retries,
262 })
263}
264
265pub fn sync_directory(dir: &Path) -> io::Result<()> {
271 #[cfg(unix)]
272 {
273 platform::sync_directory(dir)
274 }
275 #[cfg(not(unix))]
276 {
277 let _ = dir;
278 Ok(())
279 }
280}
281
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
284pub enum NameUnit {
285 Bytes,
287 Utf16,
289}
290
291#[derive(Clone, Copy, Debug, Eq, PartialEq)]
293pub struct NameLimit {
294 pub max: usize,
296 pub unit: NameUnit,
298}
299
300impl NameLimit {
301 #[must_use]
303 pub fn length(self, name: &str) -> usize {
304 match self.unit {
305 NameUnit::Bytes => name.len(),
306 NameUnit::Utf16 => name.encode_utf16().count(),
307 }
308 }
309}
310
311#[must_use]
314pub fn name_limit(dir: &Path) -> NameLimit {
315 platform::name_limit(dir)
316}
317
318#[derive(Clone, Copy, Debug, Eq, PartialEq)]
321pub struct Termination {
322 name: &'static str,
323 exit_code: u8,
324 closing: bool,
325}
326
327impl Termination {
328 #[must_use]
330 pub const fn new(name: &'static str, exit_code: u8, closing: bool) -> Self {
331 Self {
332 name,
333 exit_code,
334 closing,
335 }
336 }
337
338 #[must_use]
340 pub const fn name(self) -> &'static str {
341 self.name
342 }
343
344 #[must_use]
347 pub const fn exit_code(self) -> u8 {
348 self.exit_code
349 }
350
351 #[must_use]
354 pub const fn closing(self) -> bool {
355 self.closing
356 }
357
358 #[must_use]
360 pub fn parent_exited(self) -> bool {
361 self.name == crate::lifetime::PARENT_EXITED_NAME
362 }
363}
364
365pub fn on_termination(handler: impl Fn(Termination) + Send + Sync + 'static) -> io::Result<()> {
376 platform::on_termination(Box::new(handler))
377}
378
379#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
384pub struct AwakeInstant(#[cfg(windows)] u64, #[cfg(not(windows))] Instant);
385
386impl AwakeInstant {
387 #[must_use]
389 pub fn now() -> Self {
390 #[cfg(windows)]
391 {
392 Self(platform::unbiased_interrupt_time())
393 }
394 #[cfg(not(windows))]
395 {
396 Self(Instant::now())
397 }
398 }
399
400 #[must_use]
402 pub fn duration_since(self, earlier: Self) -> Duration {
403 #[cfg(windows)]
404 {
405 Duration::from_nanos(self.0.saturating_sub(earlier.0).saturating_mul(100))
406 }
407 #[cfg(not(windows))]
408 {
409 self.0.saturating_duration_since(earlier.0)
410 }
411 }
412
413 #[must_use]
415 pub fn elapsed(self) -> Duration {
416 Self::now().duration_since(self)
417 }
418
419 #[must_use]
421 pub fn checked_sub(self, duration: Duration) -> Option<Self> {
422 #[cfg(windows)]
423 {
424 let units = u64::try_from(duration.as_nanos() / 100).ok()?;
425 self.0.checked_sub(units).map(Self)
426 }
427 #[cfg(not(windows))]
428 {
429 self.0.checked_sub(duration).map(Self)
430 }
431 }
432}
433
434#[must_use]
437pub fn quarantined(path: &Path) -> bool {
438 #[cfg(target_os = "macos")]
439 {
440 platform::quarantined(path)
441 }
442 #[cfg(not(target_os = "macos"))]
443 {
444 let _ = path;
445 false
446 }
447}
448
449pub fn utf8_arguments(
455 arguments: impl Iterator<Item = std::ffi::OsString>,
456) -> Result<Vec<String>, String> {
457 arguments
458 .map(|argument| {
459 argument.into_string().map_err(|argument| {
460 format!(
461 "argument {:?} is not valid UTF-8",
462 argument.to_string_lossy()
463 )
464 })
465 })
466 .collect()
467}
468
469#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
475pub struct ProcessMemory {
476 pub resident_bytes: Option<u64>,
478 pub peak_resident_bytes: Option<u64>,
480 pub footprint_bytes: Option<u64>,
482 pub peak_footprint_bytes: Option<u64>,
484}
485
486#[must_use]
489pub fn file_version(path: &Path) -> Option<String> {
490 #[cfg(windows)]
491 {
492 platform::file_version(path)
493 }
494 #[cfg(not(windows))]
495 {
496 let _ = path;
497 None
498 }
499}
500
501#[must_use]
503pub fn process_memory() -> ProcessMemory {
504 #[cfg(any(unix, windows))]
505 {
506 platform::process_memory()
507 }
508 #[cfg(not(any(unix, windows)))]
509 {
510 ProcessMemory::default()
511 }
512}
513
514#[must_use]
517pub fn open_handles() -> Option<u64> {
518 #[cfg(any(unix, windows))]
519 {
520 platform::open_handles()
521 }
522 #[cfg(not(any(unix, windows)))]
523 {
524 None
525 }
526}
527
528#[must_use]
530pub fn open_file_limit() -> Option<u64> {
531 #[cfg(unix)]
532 {
533 platform::open_file_limit()
534 }
535 #[cfg(not(unix))]
536 {
537 None
538 }
539}
540
541#[must_use]
545pub fn thread_cpu_work() -> Option<u64> {
546 #[cfg(any(unix, windows))]
547 {
548 platform::thread_cpu_work()
549 }
550 #[cfg(not(any(unix, windows)))]
551 {
552 None
553 }
554}
555
556pub fn prefer_fast_cores() {
560 #[cfg(any(target_vendor = "apple", windows))]
561 platform::prefer_fast_cores();
562}
563
564pub fn limit_heap_arenas(arenas: u16) {
569 #[cfg(all(target_os = "linux", target_env = "gnu"))]
570 platform::limit_heap_arenas(arenas);
571 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
572 let _ = arenas;
573}
574
575#[must_use]
577pub fn process_cpu_time() -> Option<std::time::Duration> {
578 #[cfg(any(unix, windows))]
579 {
580 platform::process_cpu_time()
581 }
582 #[cfg(not(any(unix, windows)))]
583 {
584 None
585 }
586}
587
588#[must_use]
594pub fn host_cache_directory() -> Option<PathBuf> {
595 host_cache_directory_from(|name| std::env::var_os(name))
596}
597
598#[must_use]
600pub fn host_cache_directory_from(
601 variable: impl Fn(&str) -> Option<std::ffi::OsString>,
602) -> Option<PathBuf> {
603 let variable = |name: &str| {
604 variable(name)
605 .filter(|value| !value.to_string_lossy().trim().is_empty())
606 .map(PathBuf::from)
607 };
608 if let Some(cache) = variable("ALPHA2_HOST_CACHE_DIR") {
609 return Some(if cache.is_absolute() {
610 cache
611 } else {
612 std::env::current_dir().ok()?.join(cache)
613 });
614 }
615 if cfg!(target_os = "windows") {
616 let base = variable("LOCALAPPDATA")
617 .or_else(|| variable("USERPROFILE").map(|home| home.join("AppData").join("Local")))?;
618 return Some(base.join("alpha2"));
619 }
620 let home = variable("HOME");
621 if cfg!(target_os = "macos") {
622 return Some(home?.join("Library").join("Caches").join("alpha2"));
623 }
624 let base = variable("XDG_CACHE_HOME")
625 .filter(|path| path.is_absolute())
626 .or_else(|| home.map(|home| home.join(".cache")))?;
627 Some(base.join("alpha2"))
628}
629
630pub fn create_private_directory(path: &Path) -> io::Result<()> {
638 #[cfg(unix)]
639 {
640 platform::create_private_directory(path)
641 }
642 #[cfg(not(unix))]
643 {
644 std::fs::create_dir_all(path)
645 }
646}
647
648pub type DiagnosticSink = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
650
651static DIAGNOSTIC_SINK: std::sync::RwLock<Option<DiagnosticSink>> = std::sync::RwLock::new(None);
652
653pub fn set_diagnostic_sink(sink: Option<DiagnosticSink>) {
656 *DIAGNOSTIC_SINK
657 .write()
658 .unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
659}
660
661pub fn write_diagnostic(line: std::fmt::Arguments<'_>) {
665 let sink = DIAGNOSTIC_SINK
667 .read()
668 .unwrap_or_else(std::sync::PoisonError::into_inner)
669 .clone();
670 match sink {
671 Some(sink) => sink(&line.to_string()),
672 #[cfg(target_os = "android")]
673 None => platform::android_log(&line.to_string()),
674 #[cfg(not(target_os = "android"))]
675 None => {
676 use std::io::Write;
677 let _ = writeln!(io::stderr().lock(), "{line}");
678 }
679 }
680}
681
682#[macro_export]
684macro_rules! diagnostic {
685 ($($argument:tt)*) => {
686 $crate::write_diagnostic(::std::format_args!($($argument)*))
687 };
688}
689
690#[cfg(test)]
691mod tests {
692 use super::*;
693 use std::fs::{self, OpenOptions};
694
695 #[test]
696 fn a_diagnostic_sink_receives_each_line_until_it_is_removed() {
697 let lines = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
698 let kept = std::sync::Arc::clone(&lines);
699 set_diagnostic_sink(Some(std::sync::Arc::new(move |line: &str| {
701 if line.contains("sink-test") {
702 kept.lock().expect("lines").push(line.to_owned());
703 }
704 })));
705 diagnostic!("sink-test {}", 1);
706 set_diagnostic_sink(None);
707 diagnostic!("sink-test 2");
708 assert_eq!(*lines.lock().expect("lines"), ["sink-test 1"]);
709 }
710
711 #[test]
712 fn the_awake_clock_advances_with_time_and_never_goes_back() {
713 let started = AwakeInstant::now();
714 std::thread::sleep(Duration::from_millis(200));
715 let elapsed = started.elapsed();
716 assert!(
717 elapsed >= Duration::from_millis(150) && elapsed < Duration::from_secs(5),
718 "{elapsed:?} for a 200 ms sleep"
719 );
720 let mut last = AwakeInstant::now();
721 for _ in 0..10_000 {
722 let now = AwakeInstant::now();
723 assert!(now >= last, "{now:?} after {last:?}");
724 last = now;
725 }
726 assert_eq!(
727 started
728 .checked_sub(Duration::from_millis(1))
729 .map(|earlier| started.duration_since(earlier)),
730 Some(Duration::from_millis(1))
731 );
732 }
733
734 #[test]
735 #[cfg(unix)]
736 fn a_claimed_stream_keeps_stray_writes_out() {
737 use std::io::{Read, Write};
738 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
739 let pipe = || {
740 let mut ends = [0; 2];
741 assert_eq!(unsafe { libc::pipe(ends.as_mut_ptr()) }, 0);
743 unsafe { (File::from_raw_fd(ends[0]), OwnedFd::from_raw_fd(ends[1])) }
745 };
746 let stray = |fd: i32| {
747 unsafe { libc::write(fd, b"stray".as_ptr().cast(), 5) }
749 };
750 for diagnostics_open in [true, false] {
751 let (mut protocol_read, protocol_write) = pipe();
752 let (mut diagnostics_read, diagnostics_write) = pipe();
753 let diagnostics_fd = if diagnostics_open {
754 diagnostics_write.as_raw_fd()
755 } else {
756 -1
757 };
758 let mut claimed =
759 platform::claim_stream(protocol_write.as_raw_fd(), diagnostics_fd).expect("claim");
760 stray(protocol_write.as_raw_fd());
761 claimed.write_all(b"frame").expect("frame");
762 drop((claimed, protocol_write, diagnostics_write));
763 let mut protocol = String::new();
764 protocol_read
765 .read_to_string(&mut protocol)
766 .expect("protocol");
767 assert_eq!(protocol, "frame", "diagnostics open: {diagnostics_open}");
768 let mut diagnostics = String::new();
769 diagnostics_read
770 .read_to_string(&mut diagnostics)
771 .expect("diagnostics");
772 let expected = if diagnostics_open { "stray" } else { "" };
773 assert_eq!(diagnostics, expected);
774 }
775 }
776
777 #[test]
778 #[cfg(any(unix, windows))]
779 fn opened_files_count_as_open_handles() {
780 let path = std::env::temp_dir().join(format!("alpha2-os-handles-{}", std::process::id()));
781 fs::write(&path, b"x").expect("write");
782 let before = open_handles().expect("open handles");
783 let opened = (0..64)
785 .map(|_| File::open(&path).expect("open"))
786 .collect::<Vec<_>>();
787 let during = open_handles().expect("open handles");
788 assert!(during >= before + 32, "{before} then {during}");
789 drop(opened);
790 fs::remove_file(&path).expect("remove");
791 #[cfg(unix)]
792 assert!(open_file_limit().is_none_or(|limit| limit >= during));
793 }
794
795 #[test]
796 #[cfg(any(
797 target_os = "linux",
798 target_os = "android",
799 target_vendor = "apple",
800 windows
801 ))]
802 fn the_process_reports_its_resident_memory() {
803 let memory = process_memory();
804 let resident = memory.resident_bytes.expect("resident bytes");
805 let peak = memory.peak_resident_bytes.expect("peak resident bytes");
806 assert!(resident > 1 << 20, "{memory:?}");
807 assert!(peak >= resident, "{memory:?}");
808 }
809
810 #[test]
811 #[cfg(any(unix, windows))]
812 fn the_process_cpu_time_grows_with_its_work() {
813 let started = process_cpu_time().expect("process CPU time");
814 let mut state = 1_u64;
815 let busy = std::time::Instant::now();
816 while busy.elapsed() < std::time::Duration::from_millis(200) {
817 state = std::hint::black_box(state.wrapping_mul(6_364_136_223_846_793_005));
818 }
819 let worked = process_cpu_time()
820 .expect("process CPU time")
821 .saturating_sub(started);
822 assert!(
824 worked >= std::time::Duration::from_millis(150),
825 "{worked:?} of CPU time for 200 ms of work"
826 );
827 }
828
829 #[test]
830 #[cfg(any(unix, windows))]
831 fn the_thread_counts_the_work_it_does_and_not_the_time_it_sleeps() {
832 let started = thread_cpu_work().expect("thread work");
833 std::thread::sleep(std::time::Duration::from_millis(200));
834 let slept = thread_cpu_work().expect("thread work") - started;
835 let mut state = 1_u64;
836 let busy = std::time::Instant::now();
837 while busy.elapsed() < std::time::Duration::from_millis(200) {
838 state = std::hint::black_box(state.wrapping_mul(6_364_136_223_846_793_005));
839 }
840 let worked = thread_cpu_work().expect("thread work") - started - slept;
841 assert!(worked > slept * 4, "slept {slept}, worked {worked}");
842 }
843
844 fn scratch(name: &str) -> std::path::PathBuf {
845 let path = std::env::temp_dir().join(format!("alpha2-os-{}-{name}", std::process::id()));
846 let _ = fs::remove_file(&path);
847 path
848 }
849
850 fn open(path: &Path) -> File {
851 OpenOptions::new()
852 .read(true)
853 .write(true)
854 .create(true)
855 .truncate(false)
856 .open(path)
857 .expect("open")
858 }
859
860 pub(crate) static FORK: std::sync::Mutex<()> = std::sync::Mutex::new(());
863
864 #[test]
865 fn one_handle_at_a_time_holds_the_lock_and_closing_it_releases_it() {
866 let _fork = FORK
867 .lock()
868 .unwrap_or_else(std::sync::PoisonError::into_inner);
869 let path = scratch("lock");
870 let first = open(&path);
871 let second = open(&path);
872 assert!(try_lock_exclusive(&first).expect("lock"));
873 assert!(!try_lock_exclusive(&second).expect("second lock"));
874 drop(first);
875 assert!(try_lock_exclusive(&second).expect("lock after release"));
876 let _ = fs::remove_file(&path);
877 }
878
879 #[test]
880 fn another_handle_writes_the_whole_of_a_locked_file() {
881 use std::io::{Read, Write};
882 let path = scratch("write");
883 let lock = open(&path);
884 assert!(try_lock_exclusive(&lock).expect("lock"));
885 let mut writer = File::create(&path).expect("writer truncates and opens");
886 writer
887 .write_all(&[7_u8; 4096])
888 .expect("write under the lock");
889 drop(writer);
890 let mut read = Vec::new();
891 File::open(&path)
892 .expect("reader")
893 .read_to_end(&mut read)
894 .expect("read under the lock");
895 assert_eq!(read, vec![7_u8; 4096]);
896 drop(lock);
897 let _ = fs::remove_file(&path);
898 }
899
900 const LOCK_PROBE: &str = "ALPHA2_OS_LOCK_PROBE";
902
903 fn another_process_takes_the_lock(path: &Path) -> bool {
905 let status = std::process::Command::new(std::env::current_exe().expect("test binary"))
906 .args([
907 "--exact",
908 "tests::lock_probe_child",
909 "--ignored",
910 "--test-threads=1",
911 ])
912 .env(LOCK_PROBE, path)
913 .stdout(std::process::Stdio::null())
914 .status()
915 .expect("run the lock probe");
916 match status.code() {
917 Some(0) => true,
918 Some(3) => false,
919 _ => panic!("the lock probe failed: {status}"),
920 }
921 }
922
923 #[test]
925 #[ignore = "run by another_process_takes_the_lock"]
926 fn lock_probe_child() {
927 let path = std::env::var_os(LOCK_PROBE).expect("the parent names the file");
928 let locked = try_lock_exclusive(&open(Path::new(&path))).expect("probe lock");
929 std::process::exit(if locked { 0 } else { 3 });
930 }
931
932 #[test]
935 fn the_lock_stays_with_its_handle_when_another_handle_closes() {
936 let _fork = FORK
937 .lock()
938 .unwrap_or_else(std::sync::PoisonError::into_inner);
939 let path = scratch("other-handle");
940 let lock = open(&path);
941 assert!(try_lock_exclusive(&lock).expect("lock"));
942 drop(File::create(&path).expect("another handle opens and closes"));
943 drop(open(&path));
944 assert!(
945 !another_process_takes_the_lock(&path),
946 "closing another handle released the lock"
947 );
948 drop(lock);
949 assert!(
950 another_process_takes_the_lock(&path),
951 "closing the handle that holds the lock releases it"
952 );
953 let _ = fs::remove_file(&path);
954 }
955
956 #[test]
959 #[cfg(target_os = "linux")]
960 fn the_lock_covers_only_one_byte_no_write_reaches() {
961 use std::os::fd::AsRawFd;
962 let path = scratch("one-byte");
963 let lock = open(&path);
964 assert!(try_lock_exclusive(&lock).expect("lock"));
965 let other = open(&path);
966 let probe = |start: i64, len: i64| {
967 let mut query: libc::flock = unsafe { std::mem::zeroed() };
969 query.l_type = libc::c_short::try_from(libc::F_WRLCK).expect("F_WRLCK");
970 query.l_whence = libc::c_short::try_from(libc::SEEK_SET).expect("SEEK_SET");
971 query.l_start = start;
972 query.l_len = len;
973 let asked =
975 unsafe { libc::fcntl(other.as_raw_fd(), libc::F_OFD_GETLK, &raw mut query) };
976 assert_eq!(asked, 0, "F_OFD_GETLK: {}", io::Error::last_os_error());
977 query
978 };
979 let everything_below = probe(0, i64::MAX);
980 assert_eq!(
981 i32::from(everything_below.l_type),
982 libc::F_UNLCK,
983 "no byte a write can reach is locked"
984 );
985 let last = probe(0, 0);
986 assert_eq!(
987 i32::from(last.l_type),
988 libc::F_WRLCK,
989 "the lock is an OFD lock"
990 );
991 assert_eq!(last.l_start, i64::MAX);
993 drop(lock);
994 let _ = fs::remove_file(&path);
995 }
996
997 #[test]
998 fn a_path_moved_away_and_created_again_is_another_file() {
999 let (path, moved) = (scratch("identity"), scratch("identity-moved"));
1000 let file = open(&path);
1001 assert!(same_file(&file, &path).expect("same"));
1002 fs::rename(&path, &moved).expect("move away");
1003 assert!(!same_file(&file, &path).expect("missing"));
1004 drop(open(&path));
1005 assert!(!same_file(&file, &path).expect("replaced"));
1006 assert!(same_file(&file, &moved).expect("moved"));
1007 let _ = fs::remove_file(&path);
1008 let _ = fs::remove_file(&moved);
1009 }
1010
1011 #[test]
1012 #[cfg_attr(
1013 target_os = "android",
1014 ignore = "SELinux denies hard links to apps and the shell"
1015 )]
1016 fn a_hard_link_and_a_path_through_a_linked_directory_are_the_same_file() {
1017 let directory = scratch("identity-paths");
1018 let _ = fs::remove_dir_all(&directory);
1019 fs::create_dir(&directory).expect("directory");
1020 let (file, copy, link) = (
1021 directory.join("file"),
1022 directory.join("copy"),
1023 directory.join("link"),
1024 );
1025 fs::write(&file, b"source").expect("file");
1026 fs::write(©, b"source").expect("copy");
1027 fs::hard_link(&file, &link).expect("hard link");
1028 assert!(same_file_at(&file, &file).expect("itself"));
1029 assert!(same_file_at(&file, &link).expect("hard link"));
1030 assert!(!same_file_at(&file, ©).expect("copy"));
1031 assert!(!same_file_at(&file, &directory.join("missing")).expect("missing"));
1032 let linked = scratch("identity-paths-linked");
1033 let _ = fs::remove_file(&linked);
1034 #[cfg(unix)]
1035 std::os::unix::fs::symlink(&directory, &linked).expect("symlink");
1036 #[cfg(windows)]
1038 {
1039 let _fork = FORK
1040 .lock()
1041 .unwrap_or_else(std::sync::PoisonError::into_inner);
1042 let status = std::process::Command::new("cmd")
1043 .arg("/C")
1044 .arg("mklink")
1045 .arg("/J")
1046 .arg(&linked)
1047 .arg(&directory)
1048 .stdout(std::process::Stdio::null())
1049 .status()
1050 .expect("run mklink");
1051 assert!(status.success(), "mklink /J failed: {status}");
1052 }
1053 assert!(same_file_at(&file, &linked.join("file")).expect("through the link"));
1054 assert!(!same_file_at(©, &linked.join("file")).expect("another file"));
1055 #[cfg(unix)]
1056 fs::remove_file(&linked).expect("cleanup");
1057 #[cfg(windows)]
1058 fs::remove_dir(&linked).expect("cleanup");
1059 fs::remove_dir_all(&directory).expect("cleanup");
1060 }
1061
1062 #[test]
1063 fn a_removed_file_still_open_is_not_the_file_its_path_names() {
1064 let path = scratch("identity-removed");
1066 let file = open(&path);
1067 fs::remove_file(&path).expect("remove");
1068 assert!(!same_file(&file, &path).expect("removed"));
1069 drop(file);
1070 let again = open(&path);
1071 assert!(same_file(&again, &path).expect("created again"));
1072 drop(again);
1073 let _ = fs::remove_file(&path);
1074 }
1075
1076 #[test]
1077 fn a_publish_moves_a_file_to_a_free_name_and_never_replaces_one() {
1078 let (from, to) = (scratch("publish-from"), scratch("publish-to"));
1079 fs::write(&from, b"export").expect("from");
1080 fs::write(&to, b"someone else's").expect("to");
1081 let refused = publish_no_replace(&from, &to, &RetryPolicy::NONE)
1082 .expect_err("an existing file is not replaced");
1083 assert_eq!(refused.kind(), io::ErrorKind::AlreadyExists);
1084 assert_eq!(fs::read(&to).expect("to"), b"someone else's");
1085 assert_eq!(fs::read(&from).expect("from"), b"export");
1086 fs::remove_file(&to).expect("free the name");
1087 let (probe_from, probe_to) = (scratch("publish-probe-from"), scratch("publish-probe-to"));
1089 fs::write(&probe_from, b"probe").expect("probe");
1090 let method = match platform::rename_exclusive(&probe_from, &probe_to) {
1091 Err(error) if platform::flag_refused(&error) => PublishMethod::PlaceholderRename,
1092 answer => {
1093 answer.expect("the no-replace rename");
1094 PublishMethod::RenameNoReplace
1095 }
1096 };
1097 let _ = (fs::remove_file(&probe_from), fs::remove_file(&probe_to));
1098 let published =
1099 publish_no_replace(&from, &to, &RetryPolicy::NONE).expect("publish to a free name");
1100 assert_eq!(published, Published { method, retries: 0 });
1101 assert_eq!(fs::read(&to).expect("to"), b"export");
1102 assert!(!from.exists());
1103 let _ = fs::remove_file(&to);
1104 }
1105
1106 #[test]
1107 fn a_replacing_publish_moves_a_file_over_another() {
1108 let (from, to) = (scratch("replace-from"), scratch("replace-to"));
1109 fs::write(&from, b"export").expect("from");
1110 fs::write(&to, b"old export").expect("to");
1111 let published = publish_replace(&from, &to, &RetryPolicy::NONE).expect("replace");
1112 assert_eq!(published.method, PublishMethod::RenameReplace);
1113 assert_eq!(fs::read(&to).expect("to"), b"export");
1114 assert!(!from.exists());
1115 let _ = fs::remove_file(&to);
1116 }
1117
1118 fn flag_refused_error() -> io::Error {
1120 #[cfg(unix)]
1121 return io::Error::from_raw_os_error(libc::EINVAL);
1122 #[cfg(windows)]
1123 return io::Error::from_raw_os_error(50);
1124 }
1125
1126 #[test]
1127 fn a_file_system_without_the_no_replace_flag_publishes_through_a_placeholder() {
1128 let (from, to) = (scratch("placeholder-from"), scratch("placeholder-to"));
1129 let _ = fs::remove_file(&to);
1130 fs::write(&from, b"export").expect("from");
1131 let no_flag = |_: &Path, _: &Path| Err(flag_refused_error());
1132 let published = publish_no_replace_with(&from, &to, &RetryPolicy::NONE, &no_flag)
1133 .expect("publish through a placeholder");
1134 assert_eq!(published.method, PublishMethod::PlaceholderRename);
1135 assert_eq!(fs::read(&to).expect("to"), b"export");
1136 assert!(!from.exists());
1137 fs::write(&from, b"second export").expect("from");
1138 let refused = publish_no_replace_with(&from, &to, &RetryPolicy::NONE, &no_flag)
1139 .expect_err("an existing file is not replaced");
1140 assert_eq!(refused.kind(), io::ErrorKind::AlreadyExists);
1141 assert_eq!(fs::read(&to).expect("to"), b"export");
1142 assert_eq!(fs::read(&from).expect("from"), b"second export");
1143 let _ = fs::remove_file(&from);
1144 let _ = fs::remove_file(&to);
1145 }
1146
1147 #[test]
1150 #[cfg(unix)]
1151 fn a_publish_never_leaves_a_second_link_to_the_published_file() {
1152 use std::os::unix::fs::MetadataExt;
1153 let (from, to) = (scratch("one-link-from"), scratch("one-link-to"));
1154 let _ = fs::remove_file(&to);
1155 fs::write(&from, b"export").expect("from");
1156 let no_flag = |_: &Path, _: &Path| Err(flag_refused_error());
1157 publish_no_replace_with(&from, &to, &RetryPolicy::NONE, &no_flag).expect("publish");
1158 assert_eq!(fs::metadata(&to).expect("to").nlink(), 1);
1159 assert!(!from.exists());
1160 let _ = fs::remove_file(&to);
1161 }
1162
1163 #[test]
1164 fn a_failure_another_handle_causes_is_tried_again_until_the_budget_ends() {
1165 let busy = || io::Error::from(io::ErrorKind::ResourceBusy);
1166 let retryable = |error: &io::Error| error.kind() == io::ErrorKind::ResourceBusy;
1167 let policy = RetryPolicy {
1168 budget: Duration::from_secs(10),
1169 on_wait: &|| true,
1170 };
1171 let mut tries = 0;
1172 let (value, retries) = retrying(&policy, retryable, || {
1173 tries += 1;
1174 if tries < 3 { Err(busy()) } else { Ok(tries) }
1175 })
1176 .expect("the third try succeeds");
1177 assert_eq!((value, retries), (3, 2));
1178
1179 let short = RetryPolicy {
1180 budget: Duration::from_millis(200),
1181 on_wait: &|| true,
1182 };
1183 let started = Instant::now();
1184 let error = retrying(&short, retryable, || Err::<(), _>(busy())).expect_err("never");
1185 assert_eq!(error.kind(), io::ErrorKind::ResourceBusy);
1186 let elapsed = started.elapsed();
1187 assert!(
1188 elapsed >= Duration::from_millis(200) && elapsed < Duration::from_secs(5),
1189 "{elapsed:?}"
1190 );
1191
1192 let cancelled = RetryPolicy {
1193 budget: Duration::from_secs(10),
1194 on_wait: &|| false,
1195 };
1196 let mut tries = 0;
1197 assert!(
1198 retrying(&cancelled, retryable, || {
1199 tries += 1;
1200 Err::<(), _>(busy())
1201 })
1202 .is_err()
1203 );
1204 assert_eq!(tries, 1, "a cancelled wait stops trying");
1205
1206 let mut tries = 0;
1207 assert!(
1208 retrying(&policy, retryable, || {
1209 tries += 1;
1210 Err::<(), _>(io::Error::from(io::ErrorKind::NotFound))
1211 })
1212 .is_err()
1213 );
1214 assert_eq!(tries, 1, "another error is not tried again");
1215 }
1216
1217 #[test]
1218 #[cfg(unix)]
1219 fn a_directory_syncs() {
1220 sync_directory(&std::env::temp_dir()).expect("sync the temporary directory");
1221 }
1222
1223 #[test]
1224 fn the_name_limit_of_the_temporary_directory_is_known() {
1225 let limit = name_limit(&std::env::temp_dir());
1226 assert!(limit.max >= 143, "{limit:?}");
1227 assert_eq!(limit.length("ab"), 2);
1228 assert_eq!(
1229 limit.length("\u{d55c}"),
1230 if limit.unit == NameUnit::Bytes { 3 } else { 1 }
1231 );
1232 }
1233
1234 #[cfg(windows)]
1236 fn long_directory(label: &str) -> std::path::PathBuf {
1237 let root = scratch(label);
1238 let _ = fs::remove_dir_all(&root);
1239 let directory = root.join("a".repeat(120)).join("b".repeat(120));
1240 fs::create_dir_all(&directory).expect("long directory");
1241 directory
1242 }
1243
1244 #[test]
1245 #[cfg(windows)]
1246 fn a_publish_reaches_a_path_longer_than_max_path() {
1247 let directory = long_directory("long-path");
1248 let (from, to) = (directory.join("from.mp4"), directory.join("to.mp4"));
1249 assert!(!to.as_os_str().to_string_lossy().starts_with(r"\\?\"));
1250 assert!(to.as_os_str().len() > 260);
1251 fs::write(&from, b"export").expect("from");
1252 let published = publish_no_replace(&from, &to, &RetryPolicy::NONE).expect("no replace");
1253 assert_eq!(published.method, PublishMethod::RenameNoReplace);
1254 fs::write(&from, b"second export").expect("from");
1255 publish_replace(&from, &to, &RetryPolicy::NONE).expect("replace");
1256 assert_eq!(fs::read(&to).expect("to"), b"second export");
1257 let _ = fs::remove_dir_all(scratch("long-path"));
1258 }
1259
1260 #[cfg(windows)]
1262 fn hold_without_delete_sharing(path: &Path) -> File {
1263 use std::os::windows::fs::OpenOptionsExt;
1264 OpenOptions::new()
1265 .read(true)
1266 .share_mode(1)
1267 .open(path)
1268 .expect("hold the file")
1269 }
1270
1271 #[test]
1272 #[cfg(windows)]
1273 fn a_publish_waits_for_a_reader_without_delete_sharing() {
1274 let policy = RetryPolicy {
1275 budget: Duration::from_secs(10),
1276 on_wait: &|| true,
1277 };
1278 let (from, to) = (scratch("held-from"), scratch("held-to"));
1279 let _ = fs::remove_file(&to);
1280 fs::write(&from, b"export").expect("from");
1281 fs::write(&to, b"old export").expect("to");
1282 let holder = hold_without_delete_sharing(&to);
1283 let released = std::thread::spawn(move || {
1284 std::thread::sleep(Duration::from_millis(300));
1285 drop(holder);
1286 });
1287 let published = publish_replace(&from, &to, &policy).expect("replace once released");
1288 released.join().expect("holder");
1289 assert!(published.retries >= 1, "{published:?}");
1290 assert_eq!(fs::read(&to).expect("to"), b"export");
1291 fs::remove_file(&to).expect("free the name");
1292
1293 fs::write(&from, b"export").expect("from");
1294 let holder = hold_without_delete_sharing(&from);
1295 let released = std::thread::spawn(move || {
1296 std::thread::sleep(Duration::from_millis(300));
1297 drop(holder);
1298 });
1299 let published = publish_no_replace(&from, &to, &policy).expect("publish once released");
1300 released.join().expect("holder");
1301 assert!(published.retries >= 1, "{published:?}");
1302 fs::remove_file(&to).expect("free the name");
1303
1304 fs::write(&from, b"export").expect("from");
1305 let holder = hold_without_delete_sharing(&from);
1306 let short = RetryPolicy {
1307 budget: Duration::from_millis(500),
1308 on_wait: &|| true,
1309 };
1310 let error = publish_no_replace(&from, &to, &short).expect_err("never released");
1311 assert!(is_retryable_publish_error(&error), "{error}");
1312 drop(holder);
1313 assert!(from.exists(), "a refused publish keeps its source");
1314 let _ = fs::remove_file(&from);
1315 }
1316
1317 #[test]
1318 #[cfg(windows)]
1319 fn two_names_of_one_file_have_one_identity_and_two_files_two() {
1320 let directory = scratch("file-id");
1321 let _ = fs::remove_dir_all(&directory);
1322 fs::create_dir(&directory).expect("directory");
1323 let (file, link, copy) = (
1324 directory.join("file"),
1325 directory.join("link"),
1326 directory.join("copy"),
1327 );
1328 fs::write(&file, b"source").expect("file");
1329 fs::write(©, b"source").expect("copy");
1330 fs::hard_link(&file, &link).expect("hard link");
1331 let id = |path: &Path| {
1332 platform::file_id_info(&File::open(path).expect("open")).expect("FileIdInfo")
1333 };
1334 assert_eq!(id(&file), id(&link));
1335 assert_ne!(id(&file), id(©));
1336 assert_eq!(
1337 platform::identity(&File::open(&file).expect("open")).expect("identity"),
1338 id(&file),
1339 "NTFS answers FileIdInfo, so the 64-bit index is not used"
1340 );
1341 fs::remove_dir_all(&directory).expect("cleanup");
1342 }
1343}