Skip to main content

alpha2_os/
lib.rs

1//! Safe wrappers for the operating-system calls the native host needs that the standard library
2//! does not offer at the minimum Rust version: file locks, no-replace publishing, termination
3//! handling, parent and child lifetime, memory shared with a worker, clocks, memory, and the OS
4//! version.
5//!
6//! In iOS and Android apps the system owns the process, so the termination, parent-exit and
7//! child-lifetime calls have no use there; files, clocks, memory and the version do.
8
9use 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
47/// Takes an exclusive advisory lock on `file` without waiting. Returns `Ok(false)` when another
48/// open handle, in this or another process, holds it.
49///
50/// The lock belongs to this handle and is released when it closes or the process dies. Other
51/// handles can still read and write the whole file, so `FFmpeg` opening the same path is not
52/// affected. Where locks are mandatory, the lock covers only a byte no write can reach:
53/// - Windows: `LockFileEx` on one byte at offset `i64::MAX`.
54/// - Linux: an open-file-description lock (`F_OFD_SETLK`) on that byte. On CIFS mounts `flock`
55///   becomes a mandatory whole-file lock that would fail `FFmpeg`'s writes, and a classic `fcntl`
56///   lock is dropped when any handle of the file closes. Falls back to `flock` on `EINVAL`.
57/// - macOS and other Unix: `flock`.
58///
59/// On Linux `file` must be open for writing.
60///
61/// # Errors
62/// When the OS refuses the lock for a reason other than another holder, for example on a file
63/// system without locks.
64pub fn try_lock_exclusive(file: &File) -> io::Result<bool> {
65    platform::try_lock_exclusive(file)
66}
67
68/// Whether `path` still names the file `file` is open on. `false` when the path is gone, names a
69/// recreated file, or names a removed file kept visible by an open handle (Windows and SMB keep
70/// such names until the last handle closes).
71///
72/// # Errors
73/// When the file's identity cannot be read.
74pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
75    platform::same_file(file, path)
76}
77
78/// Whether `a` and `b` name one file (same device and inode, or volume serial and file index on
79/// Windows). Hard links and symlinks count as the same file. `false` when either path is missing.
80///
81/// # Errors
82/// When either path's identity cannot be read for a reason other than it being missing.
83pub fn same_file_at(a: &Path, b: &Path) -> io::Result<bool> {
84    platform::same_file_at(a, b)
85}
86
87/// How [`publish_no_replace`] or [`publish_replace`] moved a file into place.
88#[derive(Clone, Copy, Debug, Eq, PartialEq)]
89pub enum PublishMethod {
90    /// One rename that refuses an existing target: `renameat2(RENAME_NOREPLACE)`
91    /// on Linux, `renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` without
92    /// `MOVEFILE_REPLACE_EXISTING` on Windows.
93    RenameNoReplace,
94    /// The file system refused the no-replace flag, so an empty `O_EXCL` placeholder was created
95    /// at the target and renamed over.
96    PlaceholderRename,
97    /// A rename that replaces whatever is at the target.
98    RenameReplace,
99}
100
101impl PublishMethod {
102    /// The name used in reports.
103    #[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/// A finished file moved into place.
114#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115pub struct Published {
116    /// How it was moved.
117    pub method: PublishMethod,
118    /// Retries after errors accepted by [`is_retryable_publish_error`].
119    pub retries: u32,
120}
121
122/// How long a publish retries a step refused by another program's open handle.
123#[derive(Clone, Copy)]
124pub struct RetryPolicy<'a> {
125    /// Time from the first try after which no retry starts. Zero tries once.
126    pub budget: Duration,
127    /// Called before each wait; `false` stops and returns the last error.
128    pub on_wait: &'a dyn Fn() -> bool,
129}
130
131fn keep_waiting() -> bool {
132    true
133}
134
135impl RetryPolicy<'static> {
136    /// One try, no retries.
137    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
152// Each later wait doubles, up to `RETRY_MAX_DELAY`.
153const RETRY_FIRST_DELAY: Duration = Duration::from_millis(50);
154const RETRY_MAX_DELAY: Duration = Duration::from_secs(1);
155
156/// Runs `step` until it succeeds, fails with a non-retryable error, or `retry` stops it. Waits
157/// 50 ms before the first retry, doubling up to 1 s. Returns the value and the retry count.
158///
159/// # Errors
160/// The step's last error.
161pub 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/// Whether a publish step failed because another program (antivirus, indexer, media player)
193/// briefly holds the file open: `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION` or
194/// `ERROR_LOCK_VIOLATION` on Windows. Always `false` on Unix, where open handles do not block a
195/// rename.
196///
197/// A real permission error also reports `ERROR_ACCESS_DENIED`; retrying it costs at most the
198/// budget.
199#[must_use]
200pub fn is_retryable_publish_error(error: &io::Error) -> bool {
201    platform::is_retryable_publish_error(error)
202}
203
204/// Moves the finished file `from` to `to`, never replacing an existing file at `to`.
205///
206/// Uses the platform's no-replace rename, with verbatim (`\\?\`) paths on Windows to allow
207/// paths over `MAX_PATH`. File systems that refuse the flag (exFAT on macOS, FUSE servers such as
208/// rclone) get [`PublishMethod::PlaceholderRename`] instead. That path has two races the one-step
209/// rename lacks: a process that replaces the empty placeholder before the rename loses its file,
210/// and a crash between the two steps leaves an empty file at `to`.
211///
212/// Retryable errors are retried as `retry` allows.
213///
214/// # Errors
215/// [`io::ErrorKind::AlreadyExists`] when `to` exists, else what the operating
216/// system reports for the last try.
217pub 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
225/// [`publish_no_replace`] with an injectable rename, so tests can refuse the flag.
226fn 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
242/// Creates an empty `O_EXCL` placeholder at `to`, then renames `from` over it. A failed rename
243/// removes the placeholder if `to` still names it.
244///
245/// The placeholder must close before the rename: a FUSE server that writes back on close (rclone
246/// without a cache) would otherwise write the empty file over the published one.
247fn 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
264/// Moves the finished file `from` to `to`, replacing any file there. Retryable errors are
265/// retried as `retry` allows.
266///
267/// # Errors
268/// What the operating system reports for the last try.
269pub 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
277/// Makes renames into `dir` survive a power loss by `fsync`ing it on Unix. File systems that
278/// cannot sync a directory are not an error. No-op on Windows, where the rename writes through.
279///
280/// # Errors
281/// When the directory cannot be opened or the sync fails.
282pub 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/// What a [`NameLimit`] counts.
295#[derive(Clone, Copy, Debug, Eq, PartialEq)]
296pub enum NameUnit {
297    /// Bytes of the name's UTF-8 encoding (Unix).
298    Bytes,
299    /// UTF-16 code units (Windows).
300    Utf16,
301}
302
303/// The longest file name a directory takes.
304#[derive(Clone, Copy, Debug, Eq, PartialEq)]
305pub struct NameLimit {
306    /// Maximum name length in `unit`.
307    pub max: usize,
308    /// What `max` counts.
309    pub unit: NameUnit,
310}
311
312impl NameLimit {
313    /// The length of `name` in this limit's unit.
314    #[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/// The longest file name `dir` accepts: `pathconf(_PC_NAME_MAX)` on Unix (255 bytes if
324/// unreported), 255 UTF-16 units on Windows.
325#[must_use]
326pub fn name_limit(dir: &Path) -> NameLimit {
327    platform::name_limit(dir)
328}
329
330/// A request to end the process: an interrupt or termination signal on Unix,
331/// a console control event on Windows.
332#[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    /// Creates a termination; platform handlers and tests use this.
341    #[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    /// What asked, such as `SIGTERM` or `CTRL_C_EVENT`.
351    #[must_use]
352    pub const fn name(self) -> &'static str {
353        self.name
354    }
355
356    /// The exit status to report: `128` plus the signal number, as a shell does. On Windows an
357    /// interrupt or break maps to `130` and a close, logoff or shutdown to `143`.
358    #[must_use]
359    pub const fn exit_code(self) -> u8 {
360        self.exit_code
361    }
362
363    /// Whether the OS kills the process once the handler returns (Windows console close, logoff,
364    /// shutdown), so cleanup must finish before returning.
365    #[must_use]
366    pub const fn closing(self) -> bool {
367        self.closing
368    }
369
370    /// Whether the process that started this one exited ([`crate::watch_parent`]).
371    #[must_use]
372    pub fn parent_exited(self) -> bool {
373        self.name == crate::lifetime::PARENT_EXITED_NAME
374    }
375}
376
377/// Calls `handler` on its own thread when the process is asked to terminate, instead of ending
378/// at once. [`watch_parent`] calls the same handler.
379///
380/// On Unix it handles `SIGTERM`, `SIGINT` and `SIGHUP`; a second signal of a kind ends the process
381/// normally. On Windows it handles console control events; a second interrupt or break calls
382/// [`exit_without_handlers`]. Close, logoff and shutdown events only reach processes that have not
383/// loaded `user32.dll`. `TerminateProcess` and `SIGKILL` cannot be handled.
384///
385/// # Errors
386/// When a handler is already installed, or the operating system refuses one.
387pub fn on_termination(handler: impl Fn(Termination) + Send + Sync + 'static) -> io::Result<()> {
388    platform::on_termination(Box::new(handler))
389}
390
391/// A point on a clock that stops while the system sleeps, so stall checks ignore suspend.
392///
393/// `std::time::Instant` already stops during sleep on Linux and macOS; on Windows this reads
394/// `QueryUnbiasedInterruptTimePrecise` (100 ns units).
395#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
396pub struct AwakeInstant(#[cfg(windows)] u64, #[cfg(not(windows))] Instant);
397
398impl AwakeInstant {
399    /// The current instant.
400    #[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    /// Awake time since `earlier`, or zero when `earlier` is later.
413    #[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    /// The awake time since this one.
426    #[must_use]
427    pub fn elapsed(self) -> Duration {
428        Self::now().duration_since(self)
429    }
430
431    /// The instant `duration` earlier, if the clock reaches back that far.
432    #[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/// Whether `path` has the macOS `com.apple.quarantine` attribute, under which Gatekeeper refuses
447/// to load an unnotarized library. `false` on other systems and for unreadable files.
448#[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
461/// The arguments as UTF-8 strings. Unlike `std::env::args`, a non-UTF-8 argument is an error,
462/// not a panic.
463///
464/// # Errors
465/// A message naming the first non-UTF-8 argument, lossily decoded.
466pub 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/// The process's memory, as the operating system counts it.
482///
483/// Resident memory includes shared pages. The footprint is what memory limits and the OOM killer
484/// use: `RssAnon + RssShmem` on Linux (peak from `VmHWM`, which also counts file pages),
485/// `ri_phys_footprint` on macOS, `PrivateUsage` on Windows (peak `PeakPagefileUsage`).
486#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
487pub struct ProcessMemory {
488    /// Resident bytes now (the working set on Windows).
489    pub resident_bytes: Option<u64>,
490    /// Peak resident bytes so far.
491    pub peak_resident_bytes: Option<u64>,
492    /// Footprint bytes now.
493    pub footprint_bytes: Option<u64>,
494    /// Peak footprint bytes so far.
495    pub peak_footprint_bytes: Option<u64>,
496}
497
498/// The `major.minor.build.revision` from the Windows version resource of `path`; `None` elsewhere
499/// or without one.
500#[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/// The process's memory now and at its peak; unavailable figures are `None`.
514#[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/// Handles the process holds open: file descriptors on Unix, kernel handles on Windows. `None`
527/// where unavailable.
528#[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/// The soft limit on open file descriptors; `None` on Windows or where unlimited or unknown.
541#[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/// The calling thread's CPU work so far, comparable only with other readings on the same thread:
554/// CPU nanoseconds on Unix, cycles on Windows (`QueryThreadCycleTime`). Excludes time spent
555/// waiting for a CPU. `None` where unavailable.
556#[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
568/// Asks the scheduler to keep the calling thread on the fastest cores, so [`thread_cpu_work`]
569/// readings come from one kind of core: `QOS_CLASS_USER_INTERACTIVE` on Apple systems, no
570/// `EcoQoS` throttling on Windows, nothing elsewhere. Best effort; failures are silent.
571pub fn prefer_fast_cores() {
572    #[cfg(any(target_vendor = "apple", windows))]
573    platform::prefer_fast_cores();
574}
575
576/// Caps glibc's malloc arenas at `arenas` unless `MALLOC_ARENA_MAX` is set. Does nothing elsewhere.
577///
578/// Long-lived allocations spread over many per-thread arenas pin their pages, so a process that
579/// starts threads per request keeps growing. The cap applies to arenas created after the call.
580pub 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/// User plus system CPU time of all the process's threads so far; `None` where unavailable.
588#[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/// The host's cache directory, as the Node and Python clients name it, or `None` without a home.
601///
602/// That is `ALPHA2_HOST_CACHE_DIR` (relative to the working directory), else `alpha2` under
603/// `$XDG_CACHE_HOME` (when absolute) or `~/.cache` on Linux, `~/Library/Caches` on macOS, and
604/// `%LOCALAPPDATA%` on Windows.
605#[must_use]
606pub fn host_cache_directory() -> Option<PathBuf> {
607    host_cache_directory_from(|name| std::env::var_os(name))
608}
609
610/// [`host_cache_directory`] with the environment read through `variable`.
611#[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
642/// Creates `path` and its missing parents for files only this user may change.
643///
644/// On Unix new directories get mode 0700, and a directory is refused when another user owns it or
645/// group or others can write it.
646///
647/// # Errors
648/// When a directory cannot be created, or the existing one is refused (`PermissionDenied`).
649pub 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
660/// Receives each diagnostic line in place of the default output.
661pub 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
665/// Sends every later diagnostic line of the process to `sink`, or with `None` back to standard
666/// error, or on Android, which discards an app's standard error, to the system log as `alpha2`.
667pub fn set_diagnostic_sink(sink: Option<DiagnosticSink>) {
668    *DIAGNOSTIC_SINK
669        .write()
670        .unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
671}
672
673/// Writes one diagnostic line to the sink [`set_diagnostic_sink`] chose. The default output drops
674/// the line instead of panicking when standard error is closed, so a client closing the pipe
675/// cannot abort an export. Use [`diagnostic!`].
676pub fn write_diagnostic(line: std::fmt::Arguments<'_>) {
677    // Called outside the lock, so a sink may write diagnostics or replace itself.
678    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/// `eprintln!` through the process's diagnostic sink ([`write_diagnostic`]).
695#[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        // Other tests of this process may write while the sink is set; only marked lines count.
712        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            // SAFETY: `ends` holds the two descriptors `pipe` writes.
754            assert_eq!(unsafe { libc::pipe(ends.as_mut_ptr()) }, 0);
755            // SAFETY: both descriptors are new and owned here.
756            unsafe { (File::from_raw_fd(ends[0]), OwnedFd::from_raw_fd(ends[1])) }
757        };
758        let stray = |fd: i32| {
759            // SAFETY: the bytes are valid for the call; a write to a closed fd fails harmlessly.
760            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        // Other test threads open and close handles meanwhile, so a margin absorbs them.
796        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        // Windows CPU clocks tick in steps of up to 16 ms.
835        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    /// Serializes lock-release tests with the test that spawns a child: between `fork` and `exec`
873    /// the child holds copies of every descriptor, keeping their locks alive.
874    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    /// Names the file [`lock_probe_child`] tries to lock.
913    const LOCK_PROBE: &str = "ALPHA2_OS_LOCK_PROBE";
914
915    /// Whether a child process ([`lock_probe_child`]) can take the lock on `path`.
916    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    /// Child side of [`another_process_takes_the_lock`]: exits `0` if it got the lock, `3` if not.
936    #[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    /// `FFmpeg` opens and closes its own handles on the locked file; a per-process `fcntl` lock
945    /// would be released by the first close.
946    #[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    /// The Linux lock covers only the byte at `i64::MAX`, so CIFS still lets `FFmpeg` write the
969    /// whole file.
970    #[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            // SAFETY: an all-zero `flock` is valid; the fields the query reads are set below.
980            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            // SAFETY: `other` is open for the call and `query` outlives it.
986            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        // The kernel reports a lock reaching the last offset with `l_len` 0 (to end of file).
1004        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(&copy, 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, &copy).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        // Windows symlinks need developer mode or admin; a junction needs no privilege.
1049        #[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(&copy, &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        // SMB keeps a removed file's name until its last handle closes.
1077        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        // Expect the placeholder method on file systems that refuse the no-replace flag (exFAT).
1100        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    /// The error a file system without a no-replace rename returns.
1131    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    /// A second name for a published file would let an overwrite of either name truncate the
1160    /// other.
1161    #[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    /// A directory whose paths exceed `MAX_PATH` once a file name is added.
1247    #[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    /// Opens `path` with `FILE_SHARE_READ` only, as media players and scanners do.
1273    #[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(&copy, 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(&copy));
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}