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, clocks, memory, and the OS version.
4//!
5//! In iOS and Android apps the system owns the process, so the termination, parent-exit and
6//! child-lifetime calls have no use there; files, clocks, memory and the version do.
7
8use 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
35/// Takes an exclusive advisory lock on `file` without waiting. Returns `Ok(false)` when another
36/// open handle, in this or another process, holds it.
37///
38/// The lock belongs to this handle and is released when it closes or the process dies. Other
39/// handles can still read and write the whole file, so `FFmpeg` opening the same path is not
40/// affected. Where locks are mandatory, the lock covers only a byte no write can reach:
41/// - Windows: `LockFileEx` on one byte at offset `i64::MAX`.
42/// - Linux: an open-file-description lock (`F_OFD_SETLK`) on that byte. On CIFS mounts `flock`
43///   becomes a mandatory whole-file lock that would fail `FFmpeg`'s writes, and a classic `fcntl`
44///   lock is dropped when any handle of the file closes. Falls back to `flock` on `EINVAL`.
45/// - macOS and other Unix: `flock`.
46///
47/// On Linux `file` must be open for writing.
48///
49/// # Errors
50/// When the OS refuses the lock for a reason other than another holder, for example on a file
51/// system without locks.
52pub fn try_lock_exclusive(file: &File) -> io::Result<bool> {
53    platform::try_lock_exclusive(file)
54}
55
56/// Whether `path` still names the file `file` is open on. `false` when the path is gone, names a
57/// recreated file, or names a removed file kept visible by an open handle (Windows and SMB keep
58/// such names until the last handle closes).
59///
60/// # Errors
61/// When the file's identity cannot be read.
62pub fn same_file(file: &File, path: &Path) -> io::Result<bool> {
63    platform::same_file(file, path)
64}
65
66/// Whether `a` and `b` name one file (same device and inode, or volume serial and file index on
67/// Windows). Hard links and symlinks count as the same file. `false` when either path is missing.
68///
69/// # Errors
70/// When either path's identity cannot be read for a reason other than it being missing.
71pub fn same_file_at(a: &Path, b: &Path) -> io::Result<bool> {
72    platform::same_file_at(a, b)
73}
74
75/// How [`publish_no_replace`] or [`publish_replace`] moved a file into place.
76#[derive(Clone, Copy, Debug, Eq, PartialEq)]
77pub enum PublishMethod {
78    /// One rename that refuses an existing target: `renameat2(RENAME_NOREPLACE)`
79    /// on Linux, `renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` without
80    /// `MOVEFILE_REPLACE_EXISTING` on Windows.
81    RenameNoReplace,
82    /// The file system refused the no-replace flag, so an empty `O_EXCL` placeholder was created
83    /// at the target and renamed over.
84    PlaceholderRename,
85    /// A rename that replaces whatever is at the target.
86    RenameReplace,
87}
88
89impl PublishMethod {
90    /// The name used in reports.
91    #[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/// A finished file moved into place.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub struct Published {
104    /// How it was moved.
105    pub method: PublishMethod,
106    /// Retries after errors accepted by [`is_retryable_publish_error`].
107    pub retries: u32,
108}
109
110/// How long a publish retries a step refused by another program's open handle.
111#[derive(Clone, Copy)]
112pub struct RetryPolicy<'a> {
113    /// Time from the first try after which no retry starts. Zero tries once.
114    pub budget: Duration,
115    /// Called before each wait; `false` stops and returns the last error.
116    pub on_wait: &'a dyn Fn() -> bool,
117}
118
119fn keep_waiting() -> bool {
120    true
121}
122
123impl RetryPolicy<'static> {
124    /// One try, no retries.
125    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
140// Each later wait doubles, up to `RETRY_MAX_DELAY`.
141const RETRY_FIRST_DELAY: Duration = Duration::from_millis(50);
142const RETRY_MAX_DELAY: Duration = Duration::from_secs(1);
143
144/// Runs `step` until it succeeds, fails with a non-retryable error, or `retry` stops it. Waits
145/// 50 ms before the first retry, doubling up to 1 s. Returns the value and the retry count.
146///
147/// # Errors
148/// The step's last error.
149pub 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/// Whether a publish step failed because another program (antivirus, indexer, media player)
181/// briefly holds the file open: `ERROR_ACCESS_DENIED`, `ERROR_SHARING_VIOLATION` or
182/// `ERROR_LOCK_VIOLATION` on Windows. Always `false` on Unix, where open handles do not block a
183/// rename.
184///
185/// A real permission error also reports `ERROR_ACCESS_DENIED`; retrying it costs at most the
186/// budget.
187#[must_use]
188pub fn is_retryable_publish_error(error: &io::Error) -> bool {
189    platform::is_retryable_publish_error(error)
190}
191
192/// Moves the finished file `from` to `to`, never replacing an existing file at `to`.
193///
194/// Uses the platform's no-replace rename, with verbatim (`\\?\`) paths on Windows to allow
195/// paths over `MAX_PATH`. File systems that refuse the flag (exFAT on macOS, FUSE servers such as
196/// rclone) get [`PublishMethod::PlaceholderRename`] instead. That path has two races the one-step
197/// rename lacks: a process that replaces the empty placeholder before the rename loses its file,
198/// and a crash between the two steps leaves an empty file at `to`.
199///
200/// Retryable errors are retried as `retry` allows.
201///
202/// # Errors
203/// [`io::ErrorKind::AlreadyExists`] when `to` exists, else what the operating
204/// system reports for the last try.
205pub 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
213/// [`publish_no_replace`] with an injectable rename, so tests can refuse the flag.
214fn 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
230/// Creates an empty `O_EXCL` placeholder at `to`, then renames `from` over it. A failed rename
231/// removes the placeholder if `to` still names it.
232///
233/// The placeholder must close before the rename: a FUSE server that writes back on close (rclone
234/// without a cache) would otherwise write the empty file over the published one.
235fn 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
252/// Moves the finished file `from` to `to`, replacing any file there. Retryable errors are
253/// retried as `retry` allows.
254///
255/// # Errors
256/// What the operating system reports for the last try.
257pub 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
265/// Makes renames into `dir` survive a power loss by `fsync`ing it on Unix. File systems that
266/// cannot sync a directory are not an error. No-op on Windows, where the rename writes through.
267///
268/// # Errors
269/// When the directory cannot be opened or the sync fails.
270pub 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/// What a [`NameLimit`] counts.
283#[derive(Clone, Copy, Debug, Eq, PartialEq)]
284pub enum NameUnit {
285    /// Bytes of the name's UTF-8 encoding (Unix).
286    Bytes,
287    /// UTF-16 code units (Windows).
288    Utf16,
289}
290
291/// The longest file name a directory takes.
292#[derive(Clone, Copy, Debug, Eq, PartialEq)]
293pub struct NameLimit {
294    /// Maximum name length in `unit`.
295    pub max: usize,
296    /// What `max` counts.
297    pub unit: NameUnit,
298}
299
300impl NameLimit {
301    /// The length of `name` in this limit's unit.
302    #[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/// The longest file name `dir` accepts: `pathconf(_PC_NAME_MAX)` on Unix (255 bytes if
312/// unreported), 255 UTF-16 units on Windows.
313#[must_use]
314pub fn name_limit(dir: &Path) -> NameLimit {
315    platform::name_limit(dir)
316}
317
318/// A request to end the process: an interrupt or termination signal on Unix,
319/// a console control event on Windows.
320#[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    /// Creates a termination; platform handlers and tests use this.
329    #[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    /// What asked, such as `SIGTERM` or `CTRL_C_EVENT`.
339    #[must_use]
340    pub const fn name(self) -> &'static str {
341        self.name
342    }
343
344    /// The exit status to report: `128` plus the signal number, as a shell does. On Windows an
345    /// interrupt or break maps to `130` and a close, logoff or shutdown to `143`.
346    #[must_use]
347    pub const fn exit_code(self) -> u8 {
348        self.exit_code
349    }
350
351    /// Whether the OS kills the process once the handler returns (Windows console close, logoff,
352    /// shutdown), so cleanup must finish before returning.
353    #[must_use]
354    pub const fn closing(self) -> bool {
355        self.closing
356    }
357
358    /// Whether the process that started this one exited ([`crate::watch_parent`]).
359    #[must_use]
360    pub fn parent_exited(self) -> bool {
361        self.name == crate::lifetime::PARENT_EXITED_NAME
362    }
363}
364
365/// Calls `handler` on its own thread when the process is asked to terminate, instead of ending
366/// at once. [`watch_parent`] calls the same handler.
367///
368/// On Unix it handles `SIGTERM`, `SIGINT` and `SIGHUP`; a second signal of a kind ends the process
369/// normally. On Windows it handles console control events; a second interrupt or break calls
370/// [`exit_without_handlers`]. Close, logoff and shutdown events only reach processes that have not
371/// loaded `user32.dll`. `TerminateProcess` and `SIGKILL` cannot be handled.
372///
373/// # Errors
374/// When a handler is already installed, or the operating system refuses one.
375pub fn on_termination(handler: impl Fn(Termination) + Send + Sync + 'static) -> io::Result<()> {
376    platform::on_termination(Box::new(handler))
377}
378
379/// A point on a clock that stops while the system sleeps, so stall checks ignore suspend.
380///
381/// `std::time::Instant` already stops during sleep on Linux and macOS; on Windows this reads
382/// `QueryUnbiasedInterruptTimePrecise` (100 ns units).
383#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
384pub struct AwakeInstant(#[cfg(windows)] u64, #[cfg(not(windows))] Instant);
385
386impl AwakeInstant {
387    /// The current instant.
388    #[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    /// Awake time since `earlier`, or zero when `earlier` is later.
401    #[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    /// The awake time since this one.
414    #[must_use]
415    pub fn elapsed(self) -> Duration {
416        Self::now().duration_since(self)
417    }
418
419    /// The instant `duration` earlier, if the clock reaches back that far.
420    #[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/// Whether `path` has the macOS `com.apple.quarantine` attribute, under which Gatekeeper refuses
435/// to load an unnotarized library. `false` on other systems and for unreadable files.
436#[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
449/// The arguments as UTF-8 strings. Unlike `std::env::args`, a non-UTF-8 argument is an error,
450/// not a panic.
451///
452/// # Errors
453/// A message naming the first non-UTF-8 argument, lossily decoded.
454pub 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/// The process's memory, as the operating system counts it.
470///
471/// Resident memory includes shared pages. The footprint is what memory limits and the OOM killer
472/// use: `RssAnon + RssShmem` on Linux (peak from `VmHWM`, which also counts file pages),
473/// `ri_phys_footprint` on macOS, `PrivateUsage` on Windows (peak `PeakPagefileUsage`).
474#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
475pub struct ProcessMemory {
476    /// Resident bytes now (the working set on Windows).
477    pub resident_bytes: Option<u64>,
478    /// Peak resident bytes so far.
479    pub peak_resident_bytes: Option<u64>,
480    /// Footprint bytes now.
481    pub footprint_bytes: Option<u64>,
482    /// Peak footprint bytes so far.
483    pub peak_footprint_bytes: Option<u64>,
484}
485
486/// The `major.minor.build.revision` from the Windows version resource of `path`; `None` elsewhere
487/// or without one.
488#[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/// The process's memory now and at its peak; unavailable figures are `None`.
502#[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/// Handles the process holds open: file descriptors on Unix, kernel handles on Windows. `None`
515/// where unavailable.
516#[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/// The soft limit on open file descriptors; `None` on Windows or where unlimited or unknown.
529#[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/// The calling thread's CPU work so far, comparable only with other readings on the same thread:
542/// CPU nanoseconds on Unix, cycles on Windows (`QueryThreadCycleTime`). Excludes time spent
543/// waiting for a CPU. `None` where unavailable.
544#[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
556/// Asks the scheduler to keep the calling thread on the fastest cores, so [`thread_cpu_work`]
557/// readings come from one kind of core: `QOS_CLASS_USER_INTERACTIVE` on Apple systems, no
558/// `EcoQoS` throttling on Windows, nothing elsewhere. Best effort; failures are silent.
559pub fn prefer_fast_cores() {
560    #[cfg(any(target_vendor = "apple", windows))]
561    platform::prefer_fast_cores();
562}
563
564/// Caps glibc's malloc arenas at `arenas` unless `MALLOC_ARENA_MAX` is set. Does nothing elsewhere.
565///
566/// Long-lived allocations spread over many per-thread arenas pin their pages, so a process that
567/// starts threads per request keeps growing. The cap applies to arenas created after the call.
568pub 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/// User plus system CPU time of all the process's threads so far; `None` where unavailable.
576#[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/// The host's cache directory, as the Node and Python clients name it, or `None` without a home.
589///
590/// That is `ALPHA2_HOST_CACHE_DIR` (relative to the working directory), else `alpha2` under
591/// `$XDG_CACHE_HOME` (when absolute) or `~/.cache` on Linux, `~/Library/Caches` on macOS, and
592/// `%LOCALAPPDATA%` on Windows.
593#[must_use]
594pub fn host_cache_directory() -> Option<PathBuf> {
595    host_cache_directory_from(|name| std::env::var_os(name))
596}
597
598/// [`host_cache_directory`] with the environment read through `variable`.
599#[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
630/// Creates `path` and its missing parents for files only this user may change.
631///
632/// On Unix new directories get mode 0700, and a directory is refused when another user owns it or
633/// group or others can write it.
634///
635/// # Errors
636/// When a directory cannot be created, or the existing one is refused (`PermissionDenied`).
637pub 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
648/// Receives each diagnostic line in place of the default output.
649pub 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
653/// Sends every later diagnostic line of the process to `sink`, or with `None` back to standard
654/// error, or on Android, which discards an app's standard error, to the system log as `alpha2`.
655pub fn set_diagnostic_sink(sink: Option<DiagnosticSink>) {
656    *DIAGNOSTIC_SINK
657        .write()
658        .unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
659}
660
661/// Writes one diagnostic line to the sink [`set_diagnostic_sink`] chose. The default output drops
662/// the line instead of panicking when standard error is closed, so a client closing the pipe
663/// cannot abort an export. Use [`diagnostic!`].
664pub fn write_diagnostic(line: std::fmt::Arguments<'_>) {
665    // Called outside the lock, so a sink may write diagnostics or replace itself.
666    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/// `eprintln!` through the process's diagnostic sink ([`write_diagnostic`]).
683#[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        // Other tests of this process may write while the sink is set; only marked lines count.
700        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            // SAFETY: `ends` holds the two descriptors `pipe` writes.
742            assert_eq!(unsafe { libc::pipe(ends.as_mut_ptr()) }, 0);
743            // SAFETY: both descriptors are new and owned here.
744            unsafe { (File::from_raw_fd(ends[0]), OwnedFd::from_raw_fd(ends[1])) }
745        };
746        let stray = |fd: i32| {
747            // SAFETY: the bytes are valid for the call; a write to a closed fd fails harmlessly.
748            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        // Other test threads open and close handles meanwhile, so a margin absorbs them.
784        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        // Windows CPU clocks tick in steps of up to 16 ms.
823        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    /// Serializes lock-release tests with the test that spawns a child: between `fork` and `exec`
861    /// the child holds copies of every descriptor, keeping their locks alive.
862    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    /// Names the file [`lock_probe_child`] tries to lock.
901    const LOCK_PROBE: &str = "ALPHA2_OS_LOCK_PROBE";
902
903    /// Whether a child process ([`lock_probe_child`]) can take the lock on `path`.
904    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    /// Child side of [`another_process_takes_the_lock`]: exits `0` if it got the lock, `3` if not.
924    #[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    /// `FFmpeg` opens and closes its own handles on the locked file; a per-process `fcntl` lock
933    /// would be released by the first close.
934    #[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    /// The Linux lock covers only the byte at `i64::MAX`, so CIFS still lets `FFmpeg` write the
957    /// whole file.
958    #[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            // SAFETY: an all-zero `flock` is valid; the fields the query reads are set below.
968            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            // SAFETY: `other` is open for the call and `query` outlives it.
974            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        // The kernel reports a lock reaching the last offset with `l_len` 0 (to end of file).
992        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(&copy, 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, &copy).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        // Windows symlinks need developer mode or admin; a junction needs no privilege.
1037        #[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(&copy, &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        // SMB keeps a removed file's name until its last handle closes.
1065        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        // Expect the placeholder method on file systems that refuse the no-replace flag (exFAT).
1088        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    /// The error a file system without a no-replace rename returns.
1119    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    /// A second name for a published file would let an overwrite of either name truncate the
1148    /// other.
1149    #[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    /// A directory whose paths exceed `MAX_PATH` once a file name is added.
1235    #[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    /// Opens `path` with `FILE_SHARE_READ` only, as media players and scanners do.
1261    #[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(&copy, 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(&copy));
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}