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