Skip to main content

alpha2_host_core/
partial.rs

1//! The partial file an output is written to until it is finished, and how a
2//! finished one is published.
3//!
4//! Every transactional output writes `<stem>.a2partial.<ext>` beside its final path and
5//! moves it into place only when it finishes. A process killed without unwinding leaves the
6//! partial behind, so liveness is decided by an exclusive advisory lock the writing export
7//! holds, which the OS drops when the process ends. An unheld partial is stale and gets
8//! replaced; a held one is refused.
9//!
10//! The claim probes the folder with `<stem>.a2probe1.<ext>` and `<stem>.a2probe2.<ext>`:
11//! whether a file can be rewritten at an earlier offset (MP4 index, WAV header) and whether a
12//! rename without replacing works. A folder that cannot rename is refused before rendering;
13//! one that cannot seek (an in-order FUSE mount) gets a staging file in the temporary
14//! directory, copied in once finished.
15//!
16//! A finished partial is synced, published by [`alpha2_os::publish_no_replace`] (or
17//! [`alpha2_os::publish_replace`]), and its folder synced. A finished render is never deleted: a
18//! failed publish moves it to `<stem>.a2kept.<ext>` ([`EncodeError::Publish`]).
19//!
20//! When the tag would make a name too long, every sibling becomes
21//! `<stem prefix>~<8 hex digits>.<tag>.<ext>`, the digits a hash of the final name.
22
23use std::fs::{self, File, OpenOptions};
24use std::io::{Read, Seek, SeekFrom, Write};
25use std::path::{Path, PathBuf};
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::time::{Duration, Instant};
28
29use alpha2_media::{CancelToken, EncodeError};
30use alpha2_os::{NameLimit, NameUnit, PublishMethod, Published, RetryPolicy};
31use unicode_normalization::UnicodeNormalization;
32
33/// The absolute path, NFC-composed and lower-cased. Windows and macOS file systems usually ignore
34/// case, and macOS also normalization; the clients compare by the same rule.
35#[must_use]
36pub fn output_key(path: &Path) -> String {
37    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
38    absolute
39        .to_string_lossy()
40        .nfc()
41        .collect::<String>()
42        .to_lowercase()
43}
44
45/// The prefix of an [`EncodeError::OutputInUse`] message, when a live export writes the partial.
46pub const PARTIAL_OUTPUT_IN_USE: &str = "another export is writing this output";
47
48const TAG_PARTIAL: &str = "a2partial";
49const TAG_KEPT: &str = "a2kept";
50/// The two probe files' tags; the claim renames one to the other.
51const TAG_PROBE: [&str; 2] = ["a2probe1", "a2probe2"];
52/// The most kept files one output path gets: `a2kept`, then `a2kept2` to `a2kept99`.
53const KEPT_NAMES: u32 = 99;
54
55/// How long publishing retries while another program holds the target or partial open without
56/// sharing deletion (Windows).
57pub const PUBLISH_RETRY_BUDGET: Duration = Duration::from_secs(10);
58/// How long the claim's probe rename keeps trying the same way.
59const PROBE_RETRY_BUDGET: Duration = Duration::from_secs(2);
60/// How long a claim waits for a held lock: on macOS a child between `fork` and `exec` briefly holds
61/// a copy of a just-closed lock handle; Windows releases the locks of a terminated process after a
62/// delay that depends on system resources (`LockFileEx`).
63const CLAIM_IN_USE_WAIT: Duration = if cfg!(windows) {
64    Duration::from_secs(2)
65} else {
66    Duration::from_millis(250)
67};
68const CLAIM_IN_USE_POLL: Duration = Duration::from_millis(10);
69const STAGING_COPY_CHUNK: usize = 4 << 20;
70/// Bytes written between two syncs of an output, so the final sync flushes at most this much and
71/// a destination that stops answering is found while writing, by the stall limit.
72pub const PERIODIC_SYNC_BYTES: u64 = 256 << 20;
73
74fn output_error(error: impl std::fmt::Display) -> EncodeError {
75    EncodeError::Output(error.to_string())
76}
77
78fn output_error_at(path: &Path, error: impl std::fmt::Display) -> EncodeError {
79    EncodeError::Output(format!("{}: {error}", path.display()))
80}
81
82/// What an output does with a file already at its path.
83#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
84pub enum ExistingOutput {
85    /// Refuse it, before writing and again at the rename (the default).
86    #[default]
87    Refuse,
88    /// Replace a regular file there once the output is whole. Symlinks, devices, FIFOs, sockets
89    /// and directories are refused.
90    Replace,
91}
92
93/// Where an output goes and what it does with a file already there.
94#[derive(Clone, Debug, Eq, PartialEq)]
95pub struct OutputTarget {
96    /// The output's final path.
97    pub path: PathBuf,
98    /// What happens to a file already at `path`.
99    pub existing: ExistingOutput,
100}
101
102impl OutputTarget {
103    /// `path`, replacing a regular file there.
104    #[must_use]
105    pub fn replacing(path: impl Into<PathBuf>) -> Self {
106        Self {
107            path: path.into(),
108            existing: ExistingOutput::Replace,
109        }
110    }
111}
112
113impl From<PathBuf> for OutputTarget {
114    fn from(path: PathBuf) -> Self {
115        Self {
116            path,
117            existing: ExistingOutput::Refuse,
118        }
119    }
120}
121
122impl From<&Path> for OutputTarget {
123    fn from(path: &Path) -> Self {
124        path.to_owned().into()
125    }
126}
127
128impl From<&PathBuf> for OutputTarget {
129    fn from(path: &PathBuf) -> Self {
130        path.clone().into()
131    }
132}
133
134impl From<String> for OutputTarget {
135    fn from(path: String) -> Self {
136        PathBuf::from(path).into()
137    }
138}
139
140impl From<&String> for OutputTarget {
141    fn from(path: &String) -> Self {
142        PathBuf::from(path).into()
143    }
144}
145
146impl From<&str> for OutputTarget {
147    fn from(path: &str) -> Self {
148        PathBuf::from(path).into()
149    }
150}
151
152impl From<&OutputTarget> for OutputTarget {
153    fn from(target: &OutputTarget) -> Self {
154        target.clone()
155    }
156}
157
158/// How a finished output was published.
159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160pub struct PublishReport {
161    /// How the partial file was moved into place.
162    pub method: PublishMethod,
163    /// The folder could not seek, so the output was written to a staging file in the temporary
164    /// directory and copied in once finished.
165    pub staged_locally: bool,
166    /// Retries while another program held a file (Windows).
167    pub retries: u32,
168}
169
170/// Whether a container rewrites earlier bytes (MP4 index, WAV header), which the folder must allow.
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172pub enum SeekNeed {
173    /// The writer seeks; a folder that cannot seek gets a staging file.
174    Required,
175    /// The writer only appends.
176    NotNeeded,
177}
178
179/// How many times a claim reopens the partial when the file it locked was removed or replaced by
180/// the finishing export that held it.
181const CLAIM_ATTEMPTS: usize = 8;
182
183fn parent_dir(final_path: &Path) -> &Path {
184    final_path
185        .parent()
186        .filter(|parent| !parent.as_os_str().is_empty())
187        .unwrap_or(Path::new("."))
188}
189
190/// FNV-1a 64-bit: a fixed hash, so sibling names are the same in every process and build.
191fn fnv1a_64(bytes: &[u8]) -> u64 {
192    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
193    for byte in bytes {
194        hash ^= u64::from(*byte);
195        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
196    }
197    hash
198}
199
200/// The sibling name of `name` carrying `tag` within `limit`: `<stem>.<tag>.<ext>`, unless the
201/// longest sibling (`a2partial`) would not fit; then every sibling is
202/// `<stem prefix>~<8 hex>.<tag>.<ext>` with the low 32 bits of FNV-1a-64 over `name`.
203fn sibling_name(name: &str, stem: &str, extension: &str, tag: &str, limit: NameLimit) -> String {
204    let named = |stem: &str, tag: &str| format!("{stem}.{tag}.{extension}");
205    if limit.length(&named(stem, TAG_PARTIAL)) <= limit.max {
206        return named(stem, tag);
207    }
208    let hash = format!("~{:08x}", fnv1a_64(name.as_bytes()) & 0xffff_ffff);
209    let room = limit
210        .max
211        .saturating_sub(limit.length(&named(&hash, TAG_PARTIAL)));
212    let mut used = 0;
213    let mut prefix = 0;
214    for (index, character) in stem.char_indices() {
215        let units = match limit.unit {
216            NameUnit::Bytes => character.len_utf8(),
217            NameUnit::Utf16 => character.len_utf16(),
218        };
219        if used + units > room {
220            break;
221        }
222        used += units;
223        prefix = index + character.len_utf8();
224    }
225    named(&format!("{}{hash}", &stem[..prefix]), tag)
226}
227
228/// The sibling of `final_path` carrying `tag` ([`sibling_name`]); `bin`
229/// stands for a missing extension.
230///
231/// # Errors
232/// When the file name is not UTF-8.
233fn sibling_path(final_path: &Path, tag: &str) -> Result<PathBuf, EncodeError> {
234    let name = final_path
235        .file_name()
236        .and_then(|name| name.to_str())
237        .ok_or_else(|| EncodeError::Output("output path has no UTF-8 file name".into()))?;
238    let extension = final_path
239        .extension()
240        .and_then(|extension| extension.to_str())
241        .unwrap_or("bin");
242    let stem = final_path
243        .file_stem()
244        .and_then(|stem| stem.to_str())
245        .unwrap_or(name);
246    let limit = alpha2_os::name_limit(parent_dir(final_path));
247    Ok(final_path.with_file_name(sibling_name(name, stem, extension, tag, limit)))
248}
249
250/// `<stem>.a2partial.<ext>` beside `final_path`.
251///
252/// # Errors
253/// When the file name is not UTF-8.
254pub fn partial_output_path(final_path: &Path) -> Result<PathBuf, EncodeError> {
255    sibling_path(final_path, TAG_PARTIAL)
256}
257
258fn kept_tag(n: u32) -> String {
259    if n <= 1 {
260        TAG_KEPT.to_owned()
261    } else {
262        format!("{TAG_KEPT}{n}")
263    }
264}
265
266static NEXT_SCRATCH: AtomicU64 = AtomicU64::new(0);
267
268/// A process-unique short name in `partial`'s folder, used to rename a partial before removing it.
269fn discard_path(partial: &Path) -> PathBuf {
270    let n = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed);
271    partial.with_file_name(format!(".a2del-{}-{n}", std::process::id()))
272}
273
274fn in_use(partial: &Path) -> EncodeError {
275    EncodeError::OutputInUse(format!(
276        "{PARTIAL_OUTPUT_IN_USE}: its partial file {} is held by an export still running",
277        partial.display()
278    ))
279}
280
281/// Locks a partial file; `Ok(false)` when another handle holds it.
282type Lock<'a> = &'a mut dyn FnMut(&File) -> std::io::Result<bool>;
283
284/// Opens and locks the partial at `path`, and reports whether this call created it; `None` when it
285/// does not exist and `create` is false.
286///
287/// A held lock is retried every 10 ms for 250 ms. A file this call created but could not lock (no
288/// working locks) is removed; a pre-existing one is left, as it may be another export's.
289///
290/// # Errors
291/// [`PARTIAL_OUTPUT_IN_USE`] when another handle holds the lock, or the file system's error.
292fn lock_partial(
293    path: &Path,
294    create: bool,
295    lock: Lock<'_>,
296) -> Result<Option<(File, bool)>, EncodeError> {
297    let at = |error: std::io::Error| output_error_at(path, error);
298    let started = Instant::now();
299    let mut changes = 0;
300    while changes < CLAIM_ATTEMPTS {
301        let Some((file, created)) = open_partial(path, create).map_err(at)? else {
302            if create {
303                // Removed between two opens, or an SMB name kept until the removed file's last
304                // handle closes: look again.
305                changes += 1;
306                continue;
307            }
308            return Ok(None);
309        };
310        let locked = match lock(&file) {
311            Ok(locked) => locked,
312            Err(error) => {
313                if created && alpha2_os::same_file(&file, path).unwrap_or(false) {
314                    let _ = fs::remove_file(path);
315                }
316                return Err(at(error));
317            }
318        };
319        if !locked {
320            if started.elapsed() < CLAIM_IN_USE_WAIT {
321                drop(file);
322                std::thread::sleep(CLAIM_IN_USE_POLL);
323                continue;
324            }
325            return Err(in_use(path));
326        }
327        // The holder may have removed or renamed it between the open and the lock.
328        if alpha2_os::same_file(&file, path).map_err(at)? {
329            return Ok(Some((file, created)));
330        }
331        changes += 1;
332    }
333    Err(EncodeError::Output(format!(
334        "the partial file {} kept changing while it was claimed",
335        path.display()
336    )))
337}
338
339/// Opens the partial at `path` read-write and reports whether this call created it; `None` when
340/// nothing is there or it vanished between create and open.
341fn open_partial(path: &Path, create: bool) -> std::io::Result<Option<(File, bool)>> {
342    let mut options = OpenOptions::new();
343    options.read(true).write(true);
344    if create {
345        match options.clone().create_new(true).open(path) {
346            Ok(file) => return Ok(Some((file, true))),
347            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
348            Err(error) => return Err(error),
349        }
350    }
351    let keep_trying = || true;
352    let retry = RetryPolicy {
353        budget: PROBE_RETRY_BUDGET,
354        on_wait: &keep_trying,
355    };
356    match alpha2_os::with_publish_retries(&retry, || options.open(path)) {
357        Ok((file, _)) => Ok(Some((file, false))),
358        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
359        Err(error) => Err(error),
360    }
361}
362
363/// ` (it had <n> other names)` when the stale partial `file` has other hard links, such as a
364/// published output a crash left linked to it.
365fn other_names(file: &File) -> String {
366    #[cfg(unix)]
367    {
368        use std::os::unix::fs::MetadataExt;
369        match file.metadata().map(|metadata| metadata.nlink()) {
370            Ok(links) if links > 1 => format!(" (it had {} other names)", links - 1),
371            _ => String::new(),
372        }
373    }
374    #[cfg(not(unix))]
375    {
376        let _ = file;
377        String::new()
378    }
379}
380
381/// Where an output stands, which decides what happens to its partial if it is dropped.
382#[derive(Clone, Copy, Debug, Eq, PartialEq)]
383enum PartialState {
384    /// Being written: removed if dropped.
385    Writing,
386    /// Written and closed but not published: kept if dropped.
387    Finished,
388    /// Moved into place.
389    Published,
390    /// Moved aside after a failed publish, or left in place when even that failed.
391    Kept,
392    /// Removed.
393    Discarded,
394}
395
396/// The partial file of one output from claim to publish or removal: its path, its
397/// lock, and any staging file.
398///
399/// Sinks declare it after their writer field so the writer closes first on drop, since Windows
400/// cannot rename or remove an open file without delete sharing. Dropped while writing it removes
401/// the file; dropped finished but unpublished it keeps it ([`EncodeError::Publish`]).
402pub struct PartialOutput {
403    target: OutputTarget,
404    path: PathBuf,
405    lock: Option<File>,
406    staging: Option<PathBuf>,
407    state: PartialState,
408    /// Bytes handed to the writer since the last periodic sync ([`Self::wrote`]).
409    unsynced: u64,
410    /// The write path's length at the last sync.
411    synced_len: u64,
412}
413
414impl PartialOutput {
415    /// Claims the partial file of an output at `target`: refuses an existing output (or, replacing,
416    /// anything but a regular file), creates and locks the partial (replacing a stale one), then
417    /// probes the folder. A folder that cannot seek gets a staging file when `seek` requires it.
418    ///
419    /// # Errors
420    /// For a refused target, a partial a live export holds ([`PARTIAL_OUTPUT_IN_USE`]), a non-UTF-8
421    /// file name, a folder that cannot rename without replacing, or a file-system failure.
422    pub fn claim(target: &OutputTarget, seek: SeekNeed) -> Result<Self, EncodeError> {
423        match target.existing {
424            ExistingOutput::Refuse => {
425                if target.path.exists() {
426                    return Err(EncodeError::Output(
427                        "refusing to overwrite an existing output file".into(),
428                    ));
429                }
430            }
431            ExistingOutput::Replace => {
432                replaceable(&target.path).map_err(EncodeError::Output)?;
433                #[cfg(windows)]
434                warn_if_held(&target.path);
435            }
436        }
437        let mut claimed = Self::claim_partial_locking(target, &mut alpha2_os::try_lock_exclusive)?;
438        if !claimed.probe(seek)? && seek == SeekNeed::Required {
439            let staging = create_staging(&target.path)?;
440            alpha2_os::diagnostic!(
441                "alpha2: {} cannot rewrite a file at an earlier offset; this export is written to {} and copied there when it is finished",
442                parent_dir(&target.path).display(),
443                staging.display()
444            );
445            claimed.staging = Some(staging);
446        }
447        Ok(claimed)
448    }
449
450    /// Creates and locks `target`'s partial with `lock`, removing a stale one first. Neither
451    /// target nor folder is checked.
452    fn claim_partial_locking(target: &OutputTarget, lock: Lock<'_>) -> Result<Self, EncodeError> {
453        let path = partial_output_path(&target.path)?;
454        for _ in 0..CLAIM_ATTEMPTS {
455            let (file, created) = lock_partial(&path, true, lock)?
456                .ok_or_else(|| EncodeError::Output("the partial file was not created".into()))?;
457            if created {
458                return Ok(Self {
459                    target: target.clone(),
460                    path,
461                    lock: Some(file),
462                    staging: None,
463                    state: PartialState::Writing,
464                    unsynced: 0,
465                    synced_len: 0,
466                });
467            }
468            alpha2_os::diagnostic!(
469                "alpha2: replacing {}, a partial file no running export holds{}",
470                path.display(),
471                other_names(&file)
472            );
473            // Remove without truncating: a stale partial may be a second name of a published file.
474            let keep_trying = || true;
475            let retry = RetryPolicy {
476                budget: PROBE_RETRY_BUDGET,
477                on_wait: &keep_trying,
478            };
479            match alpha2_os::with_publish_retries(&retry, || fs::remove_file(&path)) {
480                Ok(_) => {}
481                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
482                Err(error) => return Err(output_error_at(&path, error)),
483            }
484            drop(file);
485        }
486        Err(EncodeError::Output(format!(
487            "the partial file {} kept changing while it was claimed",
488            path.display()
489        )))
490    }
491
492    /// Probes the folder with two sibling files: whether a file can be rewritten at an earlier
493    /// offset (when `seek` asks) and whether a non-replacing rename works, using the publish
494    /// ladder. Leftover probe files are this export's to remove, since it holds the lock. Returns
495    /// whether the folder can seek.
496    ///
497    /// # Errors
498    /// When the folder cannot take a non-replacing rename, or a probe file cannot be written.
499    fn probe(&self, seek: SeekNeed) -> Result<bool, EncodeError> {
500        let first = sibling_path(&self.target.path, TAG_PROBE[0])?;
501        let second = sibling_path(&self.target.path, TAG_PROBE[1])?;
502        for probe in [&first, &second] {
503            match fs::remove_file(probe) {
504                Ok(()) => {}
505                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
506                Err(error) => return Err(output_error_at(probe, error)),
507            }
508        }
509        let probed = self.probe_with(&first, &second, seek);
510        let _ = fs::remove_file(&first);
511        let _ = fs::remove_file(&second);
512        probed
513    }
514
515    fn probe_with(&self, first: &Path, second: &Path, seek: SeekNeed) -> Result<bool, EncodeError> {
516        let mut file = OpenOptions::new()
517            .write(true)
518            .create_new(true)
519            .open(first)
520            .map_err(|error| output_error_at(first, error))?;
521        let seekable = match seek {
522            SeekNeed::NotNeeded => true,
523            SeekNeed::Required => match rewrite_at_start(&mut file) {
524                Ok(()) => !hooks::not_seekable(),
525                Err(error) if cannot_seek(&error) => false,
526                Err(error) => return Err(output_error_at(first, error)),
527            },
528        };
529        drop(file);
530        let keep_trying = || true;
531        publish_no_replace(
532            first,
533            second,
534            &RetryPolicy {
535                budget: PROBE_RETRY_BUDGET,
536                on_wait: &keep_trying,
537            },
538        )
539        .map_err(|error| {
540            EncodeError::Output(format!(
541                "{} cannot take a finished file without replacing one: {error}",
542                parent_dir(&self.target.path).display()
543            ))
544        })?;
545        Ok(seekable)
546    }
547
548    /// The staging file when the folder cannot seek, the partial file otherwise.
549    #[must_use]
550    pub fn write_path(&self) -> &Path {
551        self.staging.as_deref().unwrap_or(&self.path)
552    }
553
554    /// Opens [`Self::write_path`] for this process to write.
555    ///
556    /// # Errors
557    /// When the file system refuses.
558    pub fn open_file(&self) -> Result<File, EncodeError> {
559        OpenOptions::new()
560            .write(true)
561            .open(self.write_path())
562            .map_err(output_error)
563    }
564
565    /// Adds to a write failure that the output went to a staging file, since a small temporary
566    /// directory can fill where the output folder would not.
567    #[must_use]
568    pub fn explain(&self, error: EncodeError) -> EncodeError {
569        match (error, &self.staging) {
570            (EncodeError::Adapter(message), Some(staging)) => EncodeError::Adapter(format!(
571                "{message}; the output folder cannot be written in place, so this export was written to the staging file {} first",
572                staging.display()
573            )),
574            (error, _) => error,
575        }
576    }
577
578    /// Counts `bytes` handed to the writer of [`Self::write_path`], and syncs what was written once
579    /// [`PERIODIC_SYNC_BYTES`] went since the last sync.
580    ///
581    /// # Errors
582    /// When the sync fails.
583    pub fn wrote(&mut self, bytes: u64) -> Result<(), EncodeError> {
584        self.unsynced = self.unsynced.saturating_add(bytes);
585        if self.unsynced < hooks::periodic_sync_bytes(&self.target.path) {
586            return Ok(());
587        }
588        self.unsynced = 0;
589        crate::encode_watch::beat_encode_call();
590        self.sync_written().map_err(output_error)
591    }
592
593    fn sync_written(&mut self) -> std::io::Result<()> {
594        let written = match &self.staging {
595            // Opened for writing: Windows flushes only a handle that may write.
596            Some(staging) => OpenOptions::new().write(true).open(staging)?,
597            None => self
598                .lock
599                .as_ref()
600                .ok_or_else(|| std::io::Error::other("the partial file is no longer held"))?
601                .try_clone()?,
602        };
603        let len = written.metadata()?.len();
604        hooks::sync_delay(&self.target.path, len.saturating_sub(self.synced_len));
605        written.sync_data()?;
606        hooks::record("periodic sync");
607        self.synced_len = len;
608        Ok(())
609    }
610
611    /// Publishes the finished output after its writer closed it: copies any staging file into the
612    /// partial, syncs it, moves it into place (retrying up to 10 s on Windows sharing conflicts
613    /// while beating the encode watch), and syncs the folder.
614    ///
615    /// # Errors
616    /// [`EncodeError::Cancelled`] when `cancel` stopped the staging copy or the retries (the
617    /// partial and any staging file are removed). Any other failure keeps the finished file
618    /// beside the target ([`EncodeError::Publish`]).
619    pub fn finish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
620        if self.state != PartialState::Writing {
621            return Err(EncodeError::Adapter(
622                "the output was already finished".into(),
623            ));
624        }
625        self.state = PartialState::Finished;
626        let staged_locally = self.staging.is_some();
627        if let Some(staging) = self.staging.clone() {
628            match self.copy_staging(&staging, cancel) {
629                Ok(true) => {}
630                Ok(false) => {
631                    self.state = PartialState::Writing;
632                    self.discard()?;
633                    return Err(EncodeError::Cancelled);
634                }
635                Err(error) => return Err(self.keep_staging(staging, &error)),
636            }
637        }
638        let beat_unless_cancelled = || {
639            crate::encode_watch::beat_encode_call();
640            !cancel.is_cancelled()
641        };
642        let retry = RetryPolicy {
643            budget: PUBLISH_RETRY_BUDGET,
644            on_wait: &beat_unless_cancelled,
645        };
646        match self.sync_and_publish(&retry) {
647            Ok(published) => {
648                self.state = PartialState::Published;
649                drop(self.lock.take());
650                self.remove_staging();
651                crate::encode_watch::beat_encode_call();
652                #[cfg(unix)]
653                if let Err(error) = sync_directory(parent_dir(&self.target.path)) {
654                    alpha2_os::diagnostic!(
655                        "alpha2: {} is in place, but syncing its folder failed: {error}",
656                        self.target.path.display()
657                    );
658                }
659                Ok(PublishReport {
660                    method: published.method,
661                    staged_locally,
662                    retries: published.retries,
663                })
664            }
665            Err(_) if cancel.is_cancelled() => {
666                self.state = PartialState::Writing;
667                self.discard()?;
668                Err(EncodeError::Cancelled)
669            }
670            Err(message) => Err(self.keep(message)),
671        }
672    }
673
674    /// Copies the staging file into the partial through the lock handle: an in-order FUSE server
675    /// may upload on every write-handle close, so a second handle would race. Returns `false`
676    /// when `cancel` stopped it.
677    fn copy_staging(&self, staging: &Path, cancel: &CancelToken) -> Result<bool, String> {
678        let mut source = File::open(staging).map_err(|error| error.to_string())?;
679        let mut lock = self
680            .lock
681            .as_ref()
682            .ok_or_else(|| "the partial file is no longer held".to_owned())?;
683        lock.seek(SeekFrom::Start(0))
684            .map_err(|error| error.to_string())?;
685        let mut chunk = vec![0_u8; STAGING_COPY_CHUNK];
686        let mut unsynced = 0_u64;
687        loop {
688            crate::encode_watch::beat_encode_call();
689            if cancel.is_cancelled() {
690                return Ok(false);
691            }
692            let read = source
693                .read(&mut chunk)
694                .map_err(|error| format!("reading {}: {error}", staging.display()))?;
695            if read == 0 {
696                return Ok(true);
697            }
698            lock.write_all(&chunk[..read])
699                .map_err(|error| format!("writing {}: {error}", self.path.display()))?;
700            unsynced = unsynced.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
701            if unsynced >= hooks::periodic_sync_bytes(&self.target.path) {
702                crate::encode_watch::beat_encode_call();
703                hooks::sync_delay(&self.target.path, unsynced);
704                lock.sync_data()
705                    .map_err(|error| format!("syncing {}: {error}", self.path.display()))?;
706                unsynced = 0;
707            }
708        }
709    }
710
711    /// Syncs the partial and moves it into place, or returns the failure message.
712    fn sync_and_publish(&self, retry: &RetryPolicy<'_>) -> Result<Published, String> {
713        let final_path = self.target.path.as_path();
714        let lock = self
715            .lock
716            .as_ref()
717            .ok_or_else(|| "the partial file is no longer held".to_owned())?;
718        crate::encode_watch::beat_encode_call();
719        if self.staging.is_none() {
720            let len = lock
721                .metadata()
722                .map_or(self.synced_len, |metadata| metadata.len());
723            hooks::sync_delay(final_path, len.saturating_sub(self.synced_len));
724        }
725        lock.sync_all()
726            .map_err(|error| format!("syncing {}: {error}", self.path.display()))?;
727        hooks::record("sync");
728        crate::encode_watch::beat_encode_call();
729        let published = match self.target.existing {
730            ExistingOutput::Refuse => {
731                publish_no_replace(&self.path, final_path, retry).map_err(|error| {
732                    if error.kind() == std::io::ErrorKind::AlreadyExists {
733                        format!(
734                            "a file appeared at {} while this export ran; it was left as it is",
735                            final_path.display()
736                        )
737                    } else {
738                        format!("{}: {error}", final_path.display())
739                    }
740                })
741            }
742            // Changes between this check and the rename are not guarded:
743            // the caller chose to replace.
744            ExistingOutput::Replace => replaceable(final_path).and_then(|()| {
745                alpha2_os::publish_replace(&self.path, final_path, retry)
746                    .map_err(|error| format!("{}: {error}", final_path.display()))
747            }),
748        }?;
749        hooks::record("rename");
750        Ok(published)
751    }
752
753    /// Moves the finished partial to the first free kept name after a failed
754    /// publish, and releases it.
755    fn keep(&mut self, message: String) -> EncodeError {
756        let kept = self.move_aside(&self.path);
757        self.state = PartialState::Kept;
758        drop(self.lock.take());
759        self.remove_staging();
760        match kept {
761            Ok(kept) => EncodeError::Publish {
762                message,
763                kept: Some(kept),
764            },
765            Err(error) => EncodeError::Publish {
766                message: format!(
767                    "{message}; moving it aside failed too ({error}), so it is left as {}, which the next export to this path removes",
768                    self.path.display()
769                ),
770                kept: None,
771            },
772        }
773    }
774
775    /// An uncopyable staging file is itself the kept file, left in the temporary directory; the
776    /// half-copied partial is removed.
777    fn keep_staging(&mut self, staging: PathBuf, error: &str) -> EncodeError {
778        self.staging = None;
779        self.state = PartialState::Writing;
780        let _ = self.discard();
781        self.state = PartialState::Kept;
782        EncodeError::Publish {
783            message: format!(
784                "{}: copying the finished render into {} failed: {error}",
785                self.target.path.display(),
786                self.path.display()
787            ),
788            kept: Some(staging),
789        }
790    }
791
792    /// Renames `source` to the first free kept name beside the target
793    /// without replacing, returning it.
794    fn move_aside(&self, source: &Path) -> Result<PathBuf, String> {
795        let beat = || {
796            crate::encode_watch::beat_encode_call();
797            true
798        };
799        let retry = RetryPolicy {
800            budget: PUBLISH_RETRY_BUDGET,
801            on_wait: &beat,
802        };
803        for n in 1..=KEPT_NAMES {
804            let kept =
805                sibling_path(&self.target.path, &kept_tag(n)).map_err(|error| error.to_string())?;
806            match publish_no_replace(source, &kept, &retry) {
807                Ok(_) => return Ok(kept),
808                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
809                Err(error) => return Err(format!("{}: {error}", kept.display())),
810            }
811        }
812        Err(format!(
813            "every kept name from {} to {} is taken",
814            kept_tag(1),
815            kept_tag(KEPT_NAMES)
816        ))
817    }
818
819    fn remove_staging(&mut self) {
820        if let Some(staging) = self.staging.take() {
821            let _ = fs::remove_file(staging);
822        }
823    }
824
825    /// Removes the partial of an output that will not finish.
826    ///
827    /// The partial is first renamed, still locked, to a process-private name and removed after
828    /// the lock closes, so no other export takes the name over and a FUSE server that writes
829    /// back on close writes back the discard name. If the rename fails it is removed under its
830    /// own name. A finished output is kept instead and its path printed to stderr, since no
831    /// caller receives the error.
832    ///
833    /// # Errors
834    /// When the file system refuses the removal.
835    pub fn discard(&mut self) -> Result<(), EncodeError> {
836        match self.state {
837            PartialState::Writing => {}
838            PartialState::Finished => {
839                let kept = self.keep("the export stopped before its output was published".into());
840                alpha2_os::diagnostic!("alpha2: {kept}");
841                return Ok(());
842            }
843            PartialState::Published | PartialState::Kept | PartialState::Discarded => {
844                return Ok(());
845            }
846        }
847        self.state = PartialState::Discarded;
848        self.remove_staging();
849        let Some(lock) = self.lock.take() else {
850            return Ok(());
851        };
852        let discard = discard_path(&self.path);
853        let (removed, at) = if publish_no_replace(&self.path, &discard, &RetryPolicy::NONE).is_ok()
854        {
855            close_lock(lock, &discard);
856            let keep_trying = || true;
857            let retry = RetryPolicy {
858                budget: PUBLISH_RETRY_BUDGET,
859                on_wait: &keep_trying,
860            };
861            let removed =
862                alpha2_os::with_publish_retries(&retry, || fs::remove_file(&discard)).map(|_| ());
863            (removed, discard)
864        } else {
865            let removed = fs::remove_file(&self.path);
866            close_lock(lock, &self.path);
867            (removed, self.path.clone())
868        };
869        match removed {
870            Ok(()) => Ok(()),
871            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
872            Err(error) => Err(output_error_at(&at, error)),
873        }
874    }
875}
876
877impl Drop for PartialOutput {
878    fn drop(&mut self) {
879        let _ = self.discard();
880    }
881}
882
883/// Closes the lock handle of a partial file now named `name`.
884fn close_lock(lock: File, name: &Path) {
885    drop(lock);
886    hooks::lock_closed(name);
887}
888
889/// Writes two bytes, rewrites the first and syncs, as an MP4 muxer or WAV writer does.
890fn rewrite_at_start(file: &mut File) -> std::io::Result<()> {
891    file.write_all(&[0, 0])?;
892    file.seek(SeekFrom::Start(0))?;
893    file.write_all(&[1])?;
894    file.sync_all()
895}
896
897/// Whether `error` means no rewriting at an earlier offset: `ESPIPE`, `EINVAL` or
898/// `ENOTSUP`/`EOPNOTSUPP` (in-order FUSE servers), matched by kind for portability.
899fn cannot_seek(error: &std::io::Error) -> bool {
900    matches!(
901        error.kind(),
902        std::io::ErrorKind::NotSeekable
903            | std::io::ErrorKind::InvalidInput
904            | std::io::ErrorKind::Unsupported
905    )
906}
907
908/// A new staging file in the temporary directory with the output's extension.
909fn create_staging(final_path: &Path) -> Result<PathBuf, EncodeError> {
910    let extension = final_path
911        .extension()
912        .and_then(|extension| extension.to_str())
913        .unwrap_or("bin");
914    for _ in 0..CLAIM_ATTEMPTS {
915        let n = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed);
916        let staging = std::env::temp_dir().join(format!(
917            "alpha2-staging-{}-{n}.{extension}",
918            std::process::id()
919        ));
920        match OpenOptions::new()
921            .write(true)
922            .create_new(true)
923            .open(&staging)
924        {
925            Ok(_) => return Ok(staging),
926            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
927            Err(error) => return Err(output_error_at(&staging, error)),
928        }
929    }
930    Err(EncodeError::Output(
931        "no staging file could be created in the temporary directory".into(),
932    ))
933}
934
935/// Warns on stderr that the file to replace is open without delete sharing, so the publish waits.
936#[cfg(windows)]
937fn warn_if_held(final_path: &Path) {
938    use std::os::windows::fs::OpenOptionsExt;
939    const DELETE: u32 = 0x0001_0000;
940    const SHARE_READ_WRITE_DELETE: u32 = 0x1 | 0x2 | 0x4;
941    const ERROR_SHARING_VIOLATION: i32 = 32;
942    if let Err(error) = OpenOptions::new()
943        .access_mode(DELETE)
944        .share_mode(SHARE_READ_WRITE_DELETE)
945        .open(final_path)
946        && error.raw_os_error() == Some(ERROR_SHARING_VIOLATION)
947    {
948        alpha2_os::diagnostic!(
949            "alpha2: {} is open in another program; the export will wait up to {} s for it when it finishes",
950            final_path.display(),
951            PUBLISH_RETRY_BUDGET.as_secs()
952        );
953    }
954}
955
956/// [`alpha2_os::publish_no_replace`], or what a test made it answer.
957fn publish_no_replace(
958    from: &Path,
959    to: &Path,
960    retry: &RetryPolicy<'_>,
961) -> std::io::Result<Published> {
962    if let Some(error) = hooks::publish_failure(to) {
963        return Err(error);
964    }
965    alpha2_os::publish_no_replace(from, to, retry)
966}
967
968/// [`alpha2_os::sync_directory`], recorded for a test.
969#[cfg(unix)]
970fn sync_directory(dir: &Path) -> std::io::Result<()> {
971    alpha2_os::sync_directory(dir)?;
972    hooks::record("directory sync");
973    Ok(())
974}
975
976/// Refuses a `final_path` that is not a regular file (symlink, device, FIFO, socket,
977/// directory). Nothing there is fine.
978fn replaceable(final_path: &Path) -> Result<(), String> {
979    match fs::symlink_metadata(final_path) {
980        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
981        Ok(_) => Err(format!(
982            "refusing to replace {}: not a regular file",
983            final_path.display()
984        )),
985        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
986        Err(error) => Err(format!("{}: {error}", final_path.display())),
987    }
988}
989
990/// Writes a whole file at `target`, published only once `write` has filled the claimed partial,
991/// with the same claim, sync and publish as a video output. A write failure removes the partial and
992/// leaves the target untouched. The target is checked before writing and again at the rename.
993///
994/// # Errors
995/// When the target refuses what is at its path, a live export holds the partial
996/// ([`PARTIAL_OUTPUT_IN_USE`]), `write` fails, or the file system refuses; [`EncodeError::Publish`]
997/// when the written file was kept beside the target.
998pub fn write_whole(
999    target: impl Into<OutputTarget>,
1000    write: impl FnOnce(&mut File) -> Result<(), String>,
1001) -> Result<PublishReport, EncodeError> {
1002    let target = target.into();
1003    let mut partial = PartialOutput::claim(&target, SeekNeed::NotNeeded)?;
1004    let mut file = partial.open_file()?;
1005    write(&mut file).map_err(|error| output_error_at(partial.write_path(), error))?;
1006    drop(file);
1007    partial.finish(&CancelToken::default())
1008}
1009
1010/// Writes straight-alpha 8-bit RGBA `rgba` as a PNG at `target`, published whole or not at
1011/// all like [`write_whole`].
1012///
1013/// # Errors
1014/// When `rgba` is not `width` x `height` pixels, or as [`write_whole`].
1015pub fn write_png(
1016    target: impl Into<OutputTarget>,
1017    width: u32,
1018    height: u32,
1019    rgba: &[u8],
1020) -> Result<PublishReport, EncodeError> {
1021    let expected = u64::from(width) * u64::from(height) * 4;
1022    if u64::try_from(rgba.len()).ok() != Some(expected) {
1023        return Err(EncodeError::Adapter(format!(
1024            "a {width}x{height} RGBA image is {expected} bytes, not {}",
1025            rgba.len()
1026        )));
1027    }
1028    write_whole(target, |file| {
1029        let mut buffered = std::io::BufWriter::new(file);
1030        encode_png(&mut buffered, width, height, rgba)?;
1031        buffered
1032            .into_inner()
1033            .map(|_| ())
1034            .map_err(|error| error.error().to_string())
1035    })
1036}
1037
1038/// Straight-alpha 8-bit RGBA `rgba` as the bytes of a PNG [`write_png`] would write.
1039///
1040/// # Errors
1041/// When `rgba` is not `width` x `height` pixels.
1042pub fn png_bytes(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
1043    let expected = u64::from(width) * u64::from(height) * 4;
1044    if u64::try_from(rgba.len()).ok() != Some(expected) {
1045        return Err(format!(
1046            "a {width}x{height} RGBA image is {expected} bytes, not {}",
1047            rgba.len()
1048        ));
1049    }
1050    let mut bytes = Vec::new();
1051    encode_png(&mut bytes, width, height, rgba)?;
1052    Ok(bytes)
1053}
1054
1055fn encode_png(
1056    output: &mut impl std::io::Write,
1057    width: u32,
1058    height: u32,
1059    rgba: &[u8],
1060) -> Result<(), String> {
1061    let mut encoder = png::Encoder::new(output, width, height);
1062    encoder.set_color(png::ColorType::Rgba);
1063    encoder.set_depth(png::BitDepth::Eight);
1064    // The pixels are display-encoded sRGB; tag them rather than leaving viewers to assume it.
1065    encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
1066    let mut writer = encoder.write_header().map_err(|error| error.to_string())?;
1067    writer
1068        .write_image_data(rgba)
1069        .map_err(|error| error.to_string())?;
1070    writer.finish().map_err(|error| error.to_string())
1071}
1072
1073/// Removes a sibling partial file left by an interrupted transactional export.
1074///
1075/// A partial a live export holds is not touched. Returns `false` when no partial exists.
1076///
1077/// # Errors
1078/// [`PARTIAL_OUTPUT_IN_USE`] when a live export holds it; an encoder error for an invalid target
1079/// path or a file-system failure.
1080pub fn remove_stale_partial_output(path: impl AsRef<Path>) -> Result<bool, EncodeError> {
1081    let partial = partial_output_path(path.as_ref())?;
1082    let Some((file, _)) = lock_partial(&partial, false, &mut alpha2_os::try_lock_exclusive)? else {
1083        return Ok(false);
1084    };
1085    let removed = fs::remove_file(&partial);
1086    drop(file);
1087    match removed {
1088        Ok(()) => Ok(true),
1089        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1090        Err(error) => Err(output_error(error)),
1091    }
1092}
1093
1094/// Test hooks for this thread's publishes; no-ops outside tests.
1095#[cfg(not(any(test, feature = "test-hooks")))]
1096mod hooks {
1097    use std::path::Path;
1098
1099    pub(super) fn publish_failure(_to: &Path) -> Option<std::io::Error> {
1100        None
1101    }
1102
1103    pub(super) fn not_seekable() -> bool {
1104        false
1105    }
1106
1107    pub(super) fn record(_event: &'static str) {}
1108
1109    pub(super) fn lock_closed(_name: &Path) {}
1110
1111    pub(super) const fn periodic_sync_bytes(_path: &Path) -> u64 {
1112        super::PERIODIC_SYNC_BYTES
1113    }
1114
1115    pub(super) const fn sync_delay(_path: &Path, _bytes: u64) {}
1116}
1117
1118/// Test hooks for this thread's publishes. Test builds only.
1119#[cfg(any(test, feature = "test-hooks"))]
1120#[allow(missing_docs)]
1121pub mod hooks {
1122    use std::cell::{Cell, RefCell};
1123    use std::path::{Path, PathBuf};
1124
1125    /// What [`ON_LOCK_CLOSE`] calls.
1126    pub type LockCloseHook = Box<dyn Fn(&Path)>;
1127
1128    thread_local! {
1129        /// A no-replace publish to this path fails with this OS error.
1130        pub static FAIL_PUBLISH_TO: RefCell<Option<(PathBuf, i32)>> =
1131            const { RefCell::new(None) };
1132        /// The claim's probe reports a folder that cannot seek.
1133        pub static NOT_SEEKABLE: Cell<bool> = const { Cell::new(false) };
1134        /// The publish steps taken, in order, when `Some`.
1135        pub static EVENTS: RefCell<Option<Vec<&'static str>>> =
1136            const { RefCell::new(None) };
1137        /// Called with a partial file's name when its lock handle closes.
1138        pub static ON_LOCK_CLOSE: RefCell<Option<LockCloseHook>> =
1139            const { RefCell::new(None) };
1140    }
1141
1142    pub(super) fn publish_failure(to: &Path) -> Option<std::io::Error> {
1143        FAIL_PUBLISH_TO.with_borrow(|fail| {
1144            fail.as_ref()
1145                .filter(|(path, _)| path == to)
1146                .map(|(_, code)| std::io::Error::from_raw_os_error(*code))
1147        })
1148    }
1149
1150    pub(super) fn not_seekable() -> bool {
1151        NOT_SEEKABLE.get()
1152    }
1153
1154    pub(super) fn record(event: &'static str) {
1155        EVENTS.with_borrow_mut(|events| {
1156            if let Some(events) = events {
1157                events.push(event);
1158            }
1159        });
1160    }
1161
1162    pub(super) fn lock_closed(name: &Path) {
1163        ON_LOCK_CLOSE.with_borrow(|hook| {
1164            if let Some(hook) = hook {
1165                hook(name);
1166            }
1167        });
1168    }
1169
1170    /// A slow destination for one output as (final path, bytes between periodic syncs, nanoseconds
1171    /// each sync takes per KiB it flushes). Process-wide, since syncs run on the writer's thread.
1172    pub static SLOW_SYNC: std::sync::Mutex<Option<(PathBuf, u64, u64)>> =
1173        std::sync::Mutex::new(None);
1174
1175    fn slow_sync(path: &Path) -> Option<(u64, u64)> {
1176        SLOW_SYNC
1177            .lock()
1178            .unwrap_or_else(std::sync::PoisonError::into_inner)
1179            .as_ref()
1180            .filter(|(slow, _, _)| slow == path)
1181            .map(|&(_, interval, nanos)| (interval, nanos))
1182    }
1183
1184    pub(super) fn periodic_sync_bytes(path: &Path) -> u64 {
1185        slow_sync(path).map_or(super::PERIODIC_SYNC_BYTES, |(interval, _)| interval)
1186    }
1187
1188    pub(super) fn sync_delay(path: &Path, bytes: u64) {
1189        if let Some((_, nanos)) = slow_sync(path) {
1190            std::thread::sleep(std::time::Duration::from_nanos(
1191                nanos.saturating_mul(bytes / 1024),
1192            ));
1193        }
1194    }
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199    use std::cell::RefCell;
1200    use std::io::{Read, Write};
1201
1202    use super::*;
1203
1204    #[test]
1205    fn an_output_is_synced_while_it_is_written_and_the_final_sync_covers_the_rest() {
1206        let path = final_path("periodic-sync");
1207        *hooks::SLOW_SYNC.lock().expect("hook") = Some((path.clone(), 1 << 20, 0));
1208        hooks::EVENTS.set(Some(Vec::new()));
1209        let mut partial =
1210            PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1211        let mut file = partial.open_file().expect("open");
1212        let chunk = vec![7_u8; 64 << 10];
1213        for _ in 0..56 {
1214            file.write_all(&chunk).expect("write");
1215            partial.wrote(64 << 10).expect("periodic sync");
1216        }
1217        drop(file);
1218        partial.finish(&CancelToken::default()).expect("publish");
1219        let events = hooks::EVENTS.take().expect("events");
1220        *hooks::SLOW_SYNC.lock().expect("hook") = None;
1221        let mut expected = vec!["periodic sync"; 3];
1222        expected.extend(["sync", "rename"]);
1223        if cfg!(unix) {
1224            expected.push("directory sync");
1225        }
1226        assert_eq!(events, expected);
1227        assert_eq!(fs::metadata(&path).expect("published").len(), 56 << 16);
1228        fs::remove_file(&path).ok();
1229    }
1230
1231    #[test]
1232    fn a_cancel_during_the_staging_copy_publishes_nothing_and_removes_both_files() {
1233        let path = final_path("staged-cancel");
1234        hooks::NOT_SEEKABLE.set(true);
1235        let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required);
1236        hooks::NOT_SEEKABLE.set(false);
1237        let mut partial = claimed.expect("claim");
1238        let staging = partial.write_path().to_owned();
1239        assert_ne!(staging, partial.path, "the output was not staged");
1240        let mut writer = partial.open_file().expect("the staging file opens");
1241        writer
1242            .write_all(&vec![7_u8; 3 * STAGING_COPY_CHUNK])
1243            .expect("three chunks");
1244        drop(writer);
1245        let cancel = CancelToken::default();
1246        let beats = std::cell::Cell::new(0);
1247        let watched = cancel.clone();
1248        // The copy beats once before each chunk: cancel after the first chunk is copied.
1249        let _watch = crate::encode_watch::watch_encode_calls(move || {
1250            beats.set(beats.get() + 1);
1251            if beats.get() == 2 {
1252                watched.cancel();
1253            }
1254        });
1255        assert!(matches!(
1256            partial.finish(&cancel),
1257            Err(EncodeError::Cancelled)
1258        ));
1259        assert!(!path.exists(), "the cancelled copy was published");
1260        assert!(!partial.path.exists(), "the partial was left");
1261        assert!(!staging.exists(), "the staging file was left");
1262    }
1263
1264    /// A unique final path in the temporary directory, with neither it nor its partial present.
1265    fn final_path(label: &str) -> PathBuf {
1266        let path =
1267            std::env::temp_dir().join(format!("alpha2-claim-{label}-{}.mp4", std::process::id()));
1268        let _ = fs::remove_file(&path);
1269        let _ = fs::remove_file(partial_output_path(&path).expect("partial path"));
1270        path
1271    }
1272
1273    /// The lock of a file system without working locks (`ENOLCK` on Linux).
1274    fn no_locks(_: &File) -> std::io::Result<bool> {
1275        Err(std::io::Error::other("No locks available"))
1276    }
1277
1278    #[test]
1279    fn a_partial_the_claim_created_and_could_not_lock_is_removed() {
1280        let path = final_path("unlockable");
1281        let partial = partial_output_path(&path).expect("partial path");
1282        let Err(error) =
1283            PartialOutput::claim_partial_locking(&OutputTarget::from(&path), &mut no_locks)
1284        else {
1285            panic!("a claim without a lock succeeded");
1286        };
1287        assert!(
1288            matches!(&error, EncodeError::Output(message) if message.contains(&partial.display().to_string())),
1289            "{error}"
1290        );
1291        assert!(
1292            !partial.exists(),
1293            "the refused claim left the partial it created"
1294        );
1295    }
1296
1297    #[test]
1298    fn a_partial_that_was_there_is_left_when_the_lock_fails() {
1299        let path = final_path("unlockable-existing");
1300        let partial = partial_output_path(&path).expect("partial path");
1301        fs::write(&partial, b"another export's").expect("existing partial");
1302        assert!(
1303            PartialOutput::claim_partial_locking(&OutputTarget::from(&path), &mut no_locks)
1304                .is_err()
1305        );
1306        assert_eq!(
1307            fs::read(&partial).expect("still there"),
1308            b"another export's"
1309        );
1310        fs::remove_file(&partial).expect("clean up");
1311    }
1312
1313    #[test]
1314    fn a_partial_its_holder_removes_while_it_is_claimed_is_claimed_new() {
1315        // The holder removes its partial and unlocks between this claim's open and lock. On CIFS
1316        // the removed file keeps its name until our handle closes, so the claim must not take it.
1317        let path = final_path("removed-while-claimed");
1318        let partial = partial_output_path(&path).expect("partial path");
1319        let target = OutputTarget::from(&path);
1320        let mut holder = Some(PartialOutput::claim(&target, SeekNeed::Required).expect("holder"));
1321        let claimed = PartialOutput::claim_partial_locking(&target, &mut |file| {
1322            drop(holder.take());
1323            alpha2_os::try_lock_exclusive(file)
1324        })
1325        .expect("claimed after the holder finished");
1326        assert!(holder.is_none());
1327        let mut writer = claimed.open_file().expect("the claimed partial opens");
1328        writer.write_all(b"new export").expect("write");
1329        drop(writer);
1330        let mut read = String::new();
1331        File::open(&partial)
1332            .and_then(|mut file| file.read_to_string(&mut read))
1333            .expect("read back");
1334        assert_eq!(read, "new export");
1335        drop(claimed);
1336        assert!(!partial.exists());
1337    }
1338
1339    #[test]
1340    fn a_stale_partial_is_replaced_not_emptied() {
1341        let path = final_path("stale-replaced");
1342        let partial = partial_output_path(&path).expect("partial path");
1343        fs::write(&partial, b"what a killed export left").expect("stale partial");
1344        let stale = File::open(&partial).expect("the stale file");
1345        let claimed =
1346            PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1347        assert!(
1348            !alpha2_os::same_file(&stale, &partial).expect("identity"),
1349            "the stale file was reused"
1350        );
1351        let mut bytes = Vec::new();
1352        (&stale)
1353            .read_to_end(&mut bytes)
1354            .expect("read the stale file");
1355        assert_eq!(
1356            bytes, b"what a killed export left",
1357            "the stale file was emptied"
1358        );
1359        assert_eq!(fs::read(&partial).expect("new partial"), b"");
1360        drop(claimed);
1361        assert!(!partial.exists());
1362    }
1363
1364    #[test]
1365    #[cfg(unix)]
1366    fn a_stale_partial_that_is_a_second_name_of_the_output_leaves_the_output_intact() {
1367        let path = final_path("stale-second-name");
1368        let partial = partial_output_path(&path).expect("partial path");
1369        fs::write(&path, b"the published output").expect("output");
1370        fs::hard_link(&path, &partial).expect("second name");
1371        let claimed = PartialOutput::claim(&OutputTarget::replacing(&path), SeekNeed::Required)
1372            .expect("claim");
1373        assert_eq!(
1374            fs::read(&path).expect("output"),
1375            b"the published output",
1376            "claiming the partial changed the output"
1377        );
1378        assert!(!alpha2_os::same_file_at(&path, &partial).expect("identity"));
1379        drop(claimed);
1380        assert!(!partial.exists());
1381        assert_eq!(fs::read(&path).expect("output"), b"the published output");
1382        fs::remove_file(&path).expect("clean up");
1383    }
1384
1385    #[test]
1386    fn a_held_partial_is_refused_after_a_short_wait() {
1387        let path = final_path("held-refused");
1388        let target = OutputTarget::from(&path);
1389        let held = PartialOutput::claim(&target, SeekNeed::Required).expect("holder");
1390        let started = Instant::now();
1391        let refused = PartialOutput::claim(&target, SeekNeed::Required);
1392        let waited = started.elapsed();
1393        assert!(
1394            matches!(&refused, Err(EncodeError::OutputInUse(message)) if message.starts_with(PARTIAL_OUTPUT_IN_USE)),
1395            "{:?}",
1396            refused.err()
1397        );
1398        assert!(waited >= CLAIM_IN_USE_WAIT, "refused after {waited:?}");
1399        drop(held);
1400    }
1401
1402    #[test]
1403    fn a_partial_released_within_the_wait_is_claimed() {
1404        let path = final_path("held-released");
1405        let partial = partial_output_path(&path).expect("partial path");
1406        let holder = OpenOptions::new()
1407            .read(true)
1408            .write(true)
1409            .create_new(true)
1410            .open(&partial)
1411            .expect("holder's partial");
1412        assert!(alpha2_os::try_lock_exclusive(&holder).expect("holder's lock"));
1413        let released = std::thread::spawn(move || {
1414            std::thread::sleep(Duration::from_millis(50));
1415            drop(holder);
1416        });
1417        let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required)
1418            .expect("claimed once the holder let go");
1419        released.join().expect("holder");
1420        drop(claimed);
1421        assert!(!partial.exists());
1422    }
1423
1424    #[test]
1425    #[cfg(windows)]
1426    fn a_partial_another_program_holds_open_briefly_is_claimed() {
1427        use std::os::windows::fs::OpenOptionsExt;
1428        const FILE_SHARE_READ: u32 = 1;
1429        const FILE_SHARE_WRITE: u32 = 2;
1430        for share in [FILE_SHARE_READ, FILE_SHARE_READ | FILE_SHARE_WRITE] {
1431            let path = final_path(&format!("held-open-{share}"));
1432            let partial = partial_output_path(&path).expect("partial path");
1433            fs::write(&partial, b"").expect("partial");
1434            let reader = OpenOptions::new()
1435                .read(true)
1436                .share_mode(share)
1437                .open(&partial)
1438                .expect("reader");
1439            let released = std::thread::spawn(move || {
1440                std::thread::sleep(Duration::from_millis(300));
1441                drop(reader);
1442            });
1443            let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required)
1444                .unwrap_or_else(|error| panic!("share {share}: {error}"));
1445            released.join().expect("reader");
1446            drop(claimed);
1447            assert!(!partial.exists(), "share {share}");
1448        }
1449    }
1450
1451    #[test]
1452    fn a_name_near_the_limit_gets_a_shortened_partial_name() {
1453        let directory = std::env::temp_dir();
1454        let limit = alpha2_os::name_limit(&directory);
1455        // A name 247 long in the folder's unit, which `.a2partial.mp4` pushes past 255:
1456        // 81 three-byte Hangul syllables where the limit counts bytes, 243 where it
1457        // counts UTF-16 units (Windows).
1458        let syllables = match limit.unit {
1459            alpha2_os::NameUnit::Bytes => 81,
1460            alpha2_os::NameUnit::Utf16 => 243,
1461        };
1462        let name = format!("{}.mp4", "\u{d55c}".repeat(syllables));
1463        assert_eq!(limit.length(&name), 247);
1464        let path = directory.join(&name);
1465        let _ = fs::remove_file(&path);
1466        let partial = partial_output_path(&path).expect("partial path");
1467        assert_eq!(
1468            partial,
1469            partial_output_path(&path).expect("again"),
1470            "deterministic"
1471        );
1472        let siblings = [
1473            partial.clone(),
1474            sibling_path(&path, &kept_tag(1)).expect("kept"),
1475            sibling_path(&path, &kept_tag(KEPT_NAMES)).expect("last kept"),
1476            sibling_path(&path, TAG_PROBE[0]).expect("probe"),
1477            sibling_path(&path, TAG_PROBE[1]).expect("probe"),
1478        ];
1479        for sibling in &siblings {
1480            let sibling_name = sibling
1481                .file_name()
1482                .and_then(|name| name.to_str())
1483                .expect("name");
1484            assert!(
1485                limit.length(sibling_name) <= limit.max.min(255),
1486                "{sibling_name} is {} long",
1487                limit.length(sibling_name)
1488            );
1489            assert!(sibling_name.contains('~'), "{sibling_name}");
1490        }
1491        let partial_name = partial
1492            .file_name()
1493            .and_then(|name| name.to_str())
1494            .expect("name");
1495        assert!(partial_name.starts_with('\u{d55c}'), "{partial_name}");
1496        assert!(partial_name.ends_with(".a2partial.mp4"), "{partial_name}");
1497
1498        let mut claimed =
1499            PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1500        assert!(partial.exists());
1501        // A crash leaves it unlocked; the remover derives the same name.
1502        drop(claimed.lock.take());
1503        claimed.state = PartialState::Kept;
1504        drop(claimed);
1505        assert!(remove_stale_partial_output(&path).expect("stale partial"));
1506        assert!(!partial.exists());
1507
1508        let short = directory.join("short.mp4");
1509        assert_eq!(
1510            partial_output_path(&short).expect("partial path"),
1511            directory.join("short.a2partial.mp4")
1512        );
1513    }
1514
1515    #[test]
1516    fn a_discarded_partial_leaves_nothing_even_when_its_name_is_recreated_on_close() {
1517        // A FUSE server that writes back on last handle close recreates it under its current name.
1518        let path = final_path("recreated-on-close");
1519        let partial = partial_output_path(&path).expect("partial path");
1520        let closed_as = std::rc::Rc::new(RefCell::new(None));
1521        let record = std::rc::Rc::clone(&closed_as);
1522        hooks::ON_LOCK_CLOSE.set(Some(Box::new(move |name: &Path| {
1523            fs::write(name, b"written back").expect("write back");
1524            *record.borrow_mut() = Some(name.to_owned());
1525        })));
1526        let claimed =
1527            PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1528        drop(claimed);
1529        hooks::ON_LOCK_CLOSE.set(None);
1530        let closed_as = closed_as.borrow().clone().expect("the lock closed");
1531        assert_ne!(
1532            closed_as, partial,
1533            "the lock closed under the partial's name"
1534        );
1535        assert!(!partial.exists(), "the partial name came back");
1536        assert!(
1537            !closed_as.exists(),
1538            "the written-back discard name was left"
1539        );
1540    }
1541}