1use 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};
31
32pub const PARTIAL_OUTPUT_IN_USE: &str = "another export is writing this output";
34
35const TAG_PARTIAL: &str = "a2partial";
36const TAG_KEPT: &str = "a2kept";
37const TAG_PROBE: [&str; 2] = ["a2probe1", "a2probe2"];
39const KEPT_NAMES: u32 = 99;
41
42pub const PUBLISH_RETRY_BUDGET: Duration = Duration::from_secs(10);
45const PROBE_RETRY_BUDGET: Duration = Duration::from_secs(2);
47const CLAIM_IN_USE_WAIT: Duration = if cfg!(windows) {
51 Duration::from_secs(2)
52} else {
53 Duration::from_millis(250)
54};
55const CLAIM_IN_USE_POLL: Duration = Duration::from_millis(10);
56const STAGING_COPY_CHUNK: usize = 4 << 20;
57pub const PERIODIC_SYNC_BYTES: u64 = 256 << 20;
60
61fn output_error(error: impl std::fmt::Display) -> EncodeError {
62 EncodeError::Output(error.to_string())
63}
64
65fn output_error_at(path: &Path, error: impl std::fmt::Display) -> EncodeError {
66 EncodeError::Output(format!("{}: {error}", path.display()))
67}
68
69#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
71pub enum ExistingOutput {
72 #[default]
74 Refuse,
75 Replace,
78}
79
80#[derive(Clone, Debug, Eq, PartialEq)]
82pub struct OutputTarget {
83 pub path: PathBuf,
85 pub existing: ExistingOutput,
87}
88
89impl OutputTarget {
90 #[must_use]
92 pub fn replacing(path: impl Into<PathBuf>) -> Self {
93 Self {
94 path: path.into(),
95 existing: ExistingOutput::Replace,
96 }
97 }
98}
99
100impl From<PathBuf> for OutputTarget {
101 fn from(path: PathBuf) -> Self {
102 Self {
103 path,
104 existing: ExistingOutput::Refuse,
105 }
106 }
107}
108
109impl From<&Path> for OutputTarget {
110 fn from(path: &Path) -> Self {
111 path.to_owned().into()
112 }
113}
114
115impl From<&PathBuf> for OutputTarget {
116 fn from(path: &PathBuf) -> Self {
117 path.clone().into()
118 }
119}
120
121impl From<String> for OutputTarget {
122 fn from(path: String) -> Self {
123 PathBuf::from(path).into()
124 }
125}
126
127impl From<&String> for OutputTarget {
128 fn from(path: &String) -> Self {
129 PathBuf::from(path).into()
130 }
131}
132
133impl From<&str> for OutputTarget {
134 fn from(path: &str) -> Self {
135 PathBuf::from(path).into()
136 }
137}
138
139impl From<&OutputTarget> for OutputTarget {
140 fn from(target: &OutputTarget) -> Self {
141 target.clone()
142 }
143}
144
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub struct PublishReport {
148 pub method: PublishMethod,
150 pub staged_locally: bool,
153 pub retries: u32,
155}
156
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
159pub enum SeekNeed {
160 Required,
162 NotNeeded,
164}
165
166const CLAIM_ATTEMPTS: usize = 8;
169
170fn parent_dir(final_path: &Path) -> &Path {
171 final_path
172 .parent()
173 .filter(|parent| !parent.as_os_str().is_empty())
174 .unwrap_or(Path::new("."))
175}
176
177fn fnv1a_64(bytes: &[u8]) -> u64 {
179 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
180 for byte in bytes {
181 hash ^= u64::from(*byte);
182 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
183 }
184 hash
185}
186
187fn sibling_name(name: &str, stem: &str, extension: &str, tag: &str, limit: NameLimit) -> String {
191 let named = |stem: &str, tag: &str| format!("{stem}.{tag}.{extension}");
192 if limit.length(&named(stem, TAG_PARTIAL)) <= limit.max {
193 return named(stem, tag);
194 }
195 let hash = format!("~{:08x}", fnv1a_64(name.as_bytes()) & 0xffff_ffff);
196 let room = limit
197 .max
198 .saturating_sub(limit.length(&named(&hash, TAG_PARTIAL)));
199 let mut used = 0;
200 let mut prefix = 0;
201 for (index, character) in stem.char_indices() {
202 let units = match limit.unit {
203 NameUnit::Bytes => character.len_utf8(),
204 NameUnit::Utf16 => character.len_utf16(),
205 };
206 if used + units > room {
207 break;
208 }
209 used += units;
210 prefix = index + character.len_utf8();
211 }
212 named(&format!("{}{hash}", &stem[..prefix]), tag)
213}
214
215fn sibling_path(final_path: &Path, tag: &str) -> Result<PathBuf, EncodeError> {
221 let name = final_path
222 .file_name()
223 .and_then(|name| name.to_str())
224 .ok_or_else(|| EncodeError::Output("output path has no UTF-8 file name".into()))?;
225 let extension = final_path
226 .extension()
227 .and_then(|extension| extension.to_str())
228 .unwrap_or("bin");
229 let stem = final_path
230 .file_stem()
231 .and_then(|stem| stem.to_str())
232 .unwrap_or(name);
233 let limit = alpha2_os::name_limit(parent_dir(final_path));
234 Ok(final_path.with_file_name(sibling_name(name, stem, extension, tag, limit)))
235}
236
237pub fn partial_output_path(final_path: &Path) -> Result<PathBuf, EncodeError> {
242 sibling_path(final_path, TAG_PARTIAL)
243}
244
245fn kept_tag(n: u32) -> String {
246 if n <= 1 {
247 TAG_KEPT.to_owned()
248 } else {
249 format!("{TAG_KEPT}{n}")
250 }
251}
252
253static NEXT_SCRATCH: AtomicU64 = AtomicU64::new(0);
254
255fn discard_path(partial: &Path) -> PathBuf {
257 let n = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed);
258 partial.with_file_name(format!(".a2del-{}-{n}", std::process::id()))
259}
260
261fn in_use(partial: &Path) -> EncodeError {
262 EncodeError::OutputInUse(format!(
263 "{PARTIAL_OUTPUT_IN_USE}: its partial file {} is held by an export still running",
264 partial.display()
265 ))
266}
267
268type Lock<'a> = &'a mut dyn FnMut(&File) -> std::io::Result<bool>;
270
271fn lock_partial(
280 path: &Path,
281 create: bool,
282 lock: Lock<'_>,
283) -> Result<Option<(File, bool)>, EncodeError> {
284 let at = |error: std::io::Error| output_error_at(path, error);
285 let started = Instant::now();
286 let mut changes = 0;
287 while changes < CLAIM_ATTEMPTS {
288 let Some((file, created)) = open_partial(path, create).map_err(at)? else {
289 if create {
290 changes += 1;
293 continue;
294 }
295 return Ok(None);
296 };
297 let locked = match lock(&file) {
298 Ok(locked) => locked,
299 Err(error) => {
300 if created && alpha2_os::same_file(&file, path).unwrap_or(false) {
301 let _ = fs::remove_file(path);
302 }
303 return Err(at(error));
304 }
305 };
306 if !locked {
307 if started.elapsed() < CLAIM_IN_USE_WAIT {
308 drop(file);
309 std::thread::sleep(CLAIM_IN_USE_POLL);
310 continue;
311 }
312 return Err(in_use(path));
313 }
314 if alpha2_os::same_file(&file, path).map_err(at)? {
316 return Ok(Some((file, created)));
317 }
318 changes += 1;
319 }
320 Err(EncodeError::Output(format!(
321 "the partial file {} kept changing while it was claimed",
322 path.display()
323 )))
324}
325
326fn open_partial(path: &Path, create: bool) -> std::io::Result<Option<(File, bool)>> {
329 let mut options = OpenOptions::new();
330 options.read(true).write(true);
331 if create {
332 match options.clone().create_new(true).open(path) {
333 Ok(file) => return Ok(Some((file, true))),
334 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
335 Err(error) => return Err(error),
336 }
337 }
338 let keep_trying = || true;
339 let retry = RetryPolicy {
340 budget: PROBE_RETRY_BUDGET,
341 on_wait: &keep_trying,
342 };
343 match alpha2_os::with_publish_retries(&retry, || options.open(path)) {
344 Ok((file, _)) => Ok(Some((file, false))),
345 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
346 Err(error) => Err(error),
347 }
348}
349
350fn other_names(file: &File) -> String {
353 #[cfg(unix)]
354 {
355 use std::os::unix::fs::MetadataExt;
356 match file.metadata().map(|metadata| metadata.nlink()) {
357 Ok(links) if links > 1 => format!(" (it had {} other names)", links - 1),
358 _ => String::new(),
359 }
360 }
361 #[cfg(not(unix))]
362 {
363 let _ = file;
364 String::new()
365 }
366}
367
368#[derive(Clone, Copy, Debug, Eq, PartialEq)]
370enum PartialState {
371 Writing,
373 Finished,
375 Published,
377 Kept,
379 Discarded,
381}
382
383pub struct PartialOutput {
390 target: OutputTarget,
391 path: PathBuf,
392 lock: Option<File>,
393 staging: Option<PathBuf>,
394 state: PartialState,
395 unsynced: u64,
397 synced_len: u64,
399}
400
401impl PartialOutput {
402 pub fn claim(target: &OutputTarget, seek: SeekNeed) -> Result<Self, EncodeError> {
410 match target.existing {
411 ExistingOutput::Refuse => {
412 if target.path.exists() {
413 return Err(EncodeError::Output(
414 "refusing to overwrite an existing output file".into(),
415 ));
416 }
417 }
418 ExistingOutput::Replace => {
419 replaceable(&target.path).map_err(EncodeError::Output)?;
420 #[cfg(windows)]
421 warn_if_held(&target.path);
422 }
423 }
424 let mut claimed = Self::claim_partial_locking(target, &mut alpha2_os::try_lock_exclusive)?;
425 if !claimed.probe(seek)? && seek == SeekNeed::Required {
426 let staging = create_staging(&target.path)?;
427 alpha2_os::diagnostic!(
428 "alpha2: {} cannot rewrite a file at an earlier offset; this export is written to {} and copied there when it is finished",
429 parent_dir(&target.path).display(),
430 staging.display()
431 );
432 claimed.staging = Some(staging);
433 }
434 Ok(claimed)
435 }
436
437 fn claim_partial_locking(target: &OutputTarget, lock: Lock<'_>) -> Result<Self, EncodeError> {
440 let path = partial_output_path(&target.path)?;
441 for _ in 0..CLAIM_ATTEMPTS {
442 let (file, created) = lock_partial(&path, true, lock)?
443 .ok_or_else(|| EncodeError::Output("the partial file was not created".into()))?;
444 if created {
445 return Ok(Self {
446 target: target.clone(),
447 path,
448 lock: Some(file),
449 staging: None,
450 state: PartialState::Writing,
451 unsynced: 0,
452 synced_len: 0,
453 });
454 }
455 alpha2_os::diagnostic!(
456 "alpha2: replacing {}, a partial file no running export holds{}",
457 path.display(),
458 other_names(&file)
459 );
460 let keep_trying = || true;
462 let retry = RetryPolicy {
463 budget: PROBE_RETRY_BUDGET,
464 on_wait: &keep_trying,
465 };
466 match alpha2_os::with_publish_retries(&retry, || fs::remove_file(&path)) {
467 Ok(_) => {}
468 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
469 Err(error) => return Err(output_error_at(&path, error)),
470 }
471 drop(file);
472 }
473 Err(EncodeError::Output(format!(
474 "the partial file {} kept changing while it was claimed",
475 path.display()
476 )))
477 }
478
479 fn probe(&self, seek: SeekNeed) -> Result<bool, EncodeError> {
487 let first = sibling_path(&self.target.path, TAG_PROBE[0])?;
488 let second = sibling_path(&self.target.path, TAG_PROBE[1])?;
489 for probe in [&first, &second] {
490 match fs::remove_file(probe) {
491 Ok(()) => {}
492 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
493 Err(error) => return Err(output_error_at(probe, error)),
494 }
495 }
496 let probed = self.probe_with(&first, &second, seek);
497 let _ = fs::remove_file(&first);
498 let _ = fs::remove_file(&second);
499 probed
500 }
501
502 fn probe_with(&self, first: &Path, second: &Path, seek: SeekNeed) -> Result<bool, EncodeError> {
503 let mut file = OpenOptions::new()
504 .write(true)
505 .create_new(true)
506 .open(first)
507 .map_err(|error| output_error_at(first, error))?;
508 let seekable = match seek {
509 SeekNeed::NotNeeded => true,
510 SeekNeed::Required => match rewrite_at_start(&mut file) {
511 Ok(()) => !hooks::not_seekable(),
512 Err(error) if cannot_seek(&error) => false,
513 Err(error) => return Err(output_error_at(first, error)),
514 },
515 };
516 drop(file);
517 let keep_trying = || true;
518 publish_no_replace(
519 first,
520 second,
521 &RetryPolicy {
522 budget: PROBE_RETRY_BUDGET,
523 on_wait: &keep_trying,
524 },
525 )
526 .map_err(|error| {
527 EncodeError::Output(format!(
528 "{} cannot take a finished file without replacing one: {error}",
529 parent_dir(&self.target.path).display()
530 ))
531 })?;
532 Ok(seekable)
533 }
534
535 #[must_use]
537 pub fn write_path(&self) -> &Path {
538 self.staging.as_deref().unwrap_or(&self.path)
539 }
540
541 pub fn open_file(&self) -> Result<File, EncodeError> {
546 OpenOptions::new()
547 .write(true)
548 .open(self.write_path())
549 .map_err(output_error)
550 }
551
552 #[must_use]
555 pub fn explain(&self, error: EncodeError) -> EncodeError {
556 match (error, &self.staging) {
557 (EncodeError::Adapter(message), Some(staging)) => EncodeError::Adapter(format!(
558 "{message}; the output folder cannot be written in place, so this export was written to the staging file {} first",
559 staging.display()
560 )),
561 (error, _) => error,
562 }
563 }
564
565 pub fn wrote(&mut self, bytes: u64) -> Result<(), EncodeError> {
571 self.unsynced = self.unsynced.saturating_add(bytes);
572 if self.unsynced < hooks::periodic_sync_bytes(&self.target.path) {
573 return Ok(());
574 }
575 self.unsynced = 0;
576 crate::encode_watch::beat_encode_call();
577 self.sync_written().map_err(output_error)
578 }
579
580 fn sync_written(&mut self) -> std::io::Result<()> {
581 let written = match &self.staging {
582 Some(staging) => OpenOptions::new().write(true).open(staging)?,
584 None => self
585 .lock
586 .as_ref()
587 .ok_or_else(|| std::io::Error::other("the partial file is no longer held"))?
588 .try_clone()?,
589 };
590 let len = written.metadata()?.len();
591 hooks::sync_delay(&self.target.path, len.saturating_sub(self.synced_len));
592 written.sync_data()?;
593 hooks::record("periodic sync");
594 self.synced_len = len;
595 Ok(())
596 }
597
598 pub fn finish(&mut self, cancel: &CancelToken) -> Result<PublishReport, EncodeError> {
607 if self.state != PartialState::Writing {
608 return Err(EncodeError::Adapter(
609 "the output was already finished".into(),
610 ));
611 }
612 self.state = PartialState::Finished;
613 let staged_locally = self.staging.is_some();
614 if let Some(staging) = self.staging.clone() {
615 match self.copy_staging(&staging, cancel) {
616 Ok(true) => {}
617 Ok(false) => {
618 self.state = PartialState::Writing;
619 self.discard()?;
620 return Err(EncodeError::Cancelled);
621 }
622 Err(error) => return Err(self.keep_staging(staging, &error)),
623 }
624 }
625 let beat_unless_cancelled = || {
626 crate::encode_watch::beat_encode_call();
627 !cancel.is_cancelled()
628 };
629 let retry = RetryPolicy {
630 budget: PUBLISH_RETRY_BUDGET,
631 on_wait: &beat_unless_cancelled,
632 };
633 match self.sync_and_publish(&retry) {
634 Ok(published) => {
635 self.state = PartialState::Published;
636 drop(self.lock.take());
637 self.remove_staging();
638 crate::encode_watch::beat_encode_call();
639 #[cfg(unix)]
640 if let Err(error) = sync_directory(parent_dir(&self.target.path)) {
641 alpha2_os::diagnostic!(
642 "alpha2: {} is in place, but syncing its folder failed: {error}",
643 self.target.path.display()
644 );
645 }
646 Ok(PublishReport {
647 method: published.method,
648 staged_locally,
649 retries: published.retries,
650 })
651 }
652 Err(_) if cancel.is_cancelled() => {
653 self.state = PartialState::Writing;
654 self.discard()?;
655 Err(EncodeError::Cancelled)
656 }
657 Err(message) => Err(self.keep(message)),
658 }
659 }
660
661 fn copy_staging(&self, staging: &Path, cancel: &CancelToken) -> Result<bool, String> {
665 let mut source = File::open(staging).map_err(|error| error.to_string())?;
666 let mut lock = self
667 .lock
668 .as_ref()
669 .ok_or_else(|| "the partial file is no longer held".to_owned())?;
670 lock.seek(SeekFrom::Start(0))
671 .map_err(|error| error.to_string())?;
672 let mut chunk = vec![0_u8; STAGING_COPY_CHUNK];
673 let mut unsynced = 0_u64;
674 loop {
675 crate::encode_watch::beat_encode_call();
676 if cancel.is_cancelled() {
677 return Ok(false);
678 }
679 let read = source
680 .read(&mut chunk)
681 .map_err(|error| format!("reading {}: {error}", staging.display()))?;
682 if read == 0 {
683 return Ok(true);
684 }
685 lock.write_all(&chunk[..read])
686 .map_err(|error| format!("writing {}: {error}", self.path.display()))?;
687 unsynced = unsynced.saturating_add(u64::try_from(read).unwrap_or(u64::MAX));
688 if unsynced >= hooks::periodic_sync_bytes(&self.target.path) {
689 crate::encode_watch::beat_encode_call();
690 hooks::sync_delay(&self.target.path, unsynced);
691 lock.sync_data()
692 .map_err(|error| format!("syncing {}: {error}", self.path.display()))?;
693 unsynced = 0;
694 }
695 }
696 }
697
698 fn sync_and_publish(&self, retry: &RetryPolicy<'_>) -> Result<Published, String> {
700 let final_path = self.target.path.as_path();
701 let lock = self
702 .lock
703 .as_ref()
704 .ok_or_else(|| "the partial file is no longer held".to_owned())?;
705 crate::encode_watch::beat_encode_call();
706 if self.staging.is_none() {
707 let len = lock
708 .metadata()
709 .map_or(self.synced_len, |metadata| metadata.len());
710 hooks::sync_delay(final_path, len.saturating_sub(self.synced_len));
711 }
712 lock.sync_all()
713 .map_err(|error| format!("syncing {}: {error}", self.path.display()))?;
714 hooks::record("sync");
715 crate::encode_watch::beat_encode_call();
716 let published = match self.target.existing {
717 ExistingOutput::Refuse => {
718 publish_no_replace(&self.path, final_path, retry).map_err(|error| {
719 if error.kind() == std::io::ErrorKind::AlreadyExists {
720 format!(
721 "a file appeared at {} while this export ran; it was left as it is",
722 final_path.display()
723 )
724 } else {
725 format!("{}: {error}", final_path.display())
726 }
727 })
728 }
729 ExistingOutput::Replace => replaceable(final_path).and_then(|()| {
732 alpha2_os::publish_replace(&self.path, final_path, retry)
733 .map_err(|error| format!("{}: {error}", final_path.display()))
734 }),
735 }?;
736 hooks::record("rename");
737 Ok(published)
738 }
739
740 fn keep(&mut self, message: String) -> EncodeError {
743 let kept = self.move_aside(&self.path);
744 self.state = PartialState::Kept;
745 drop(self.lock.take());
746 self.remove_staging();
747 match kept {
748 Ok(kept) => EncodeError::Publish {
749 message,
750 kept: Some(kept),
751 },
752 Err(error) => EncodeError::Publish {
753 message: format!(
754 "{message}; moving it aside failed too ({error}), so it is left as {}, which the next export to this path removes",
755 self.path.display()
756 ),
757 kept: None,
758 },
759 }
760 }
761
762 fn keep_staging(&mut self, staging: PathBuf, error: &str) -> EncodeError {
765 self.staging = None;
766 self.state = PartialState::Writing;
767 let _ = self.discard();
768 self.state = PartialState::Kept;
769 EncodeError::Publish {
770 message: format!(
771 "{}: copying the finished render into {} failed: {error}",
772 self.target.path.display(),
773 self.path.display()
774 ),
775 kept: Some(staging),
776 }
777 }
778
779 fn move_aside(&self, source: &Path) -> Result<PathBuf, String> {
782 let beat = || {
783 crate::encode_watch::beat_encode_call();
784 true
785 };
786 let retry = RetryPolicy {
787 budget: PUBLISH_RETRY_BUDGET,
788 on_wait: &beat,
789 };
790 for n in 1..=KEPT_NAMES {
791 let kept =
792 sibling_path(&self.target.path, &kept_tag(n)).map_err(|error| error.to_string())?;
793 match publish_no_replace(source, &kept, &retry) {
794 Ok(_) => return Ok(kept),
795 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
796 Err(error) => return Err(format!("{}: {error}", kept.display())),
797 }
798 }
799 Err(format!(
800 "every kept name from {} to {} is taken",
801 kept_tag(1),
802 kept_tag(KEPT_NAMES)
803 ))
804 }
805
806 fn remove_staging(&mut self) {
807 if let Some(staging) = self.staging.take() {
808 let _ = fs::remove_file(staging);
809 }
810 }
811
812 pub fn discard(&mut self) -> Result<(), EncodeError> {
823 match self.state {
824 PartialState::Writing => {}
825 PartialState::Finished => {
826 let kept = self.keep("the export stopped before its output was published".into());
827 alpha2_os::diagnostic!("alpha2: {kept}");
828 return Ok(());
829 }
830 PartialState::Published | PartialState::Kept | PartialState::Discarded => {
831 return Ok(());
832 }
833 }
834 self.state = PartialState::Discarded;
835 self.remove_staging();
836 let Some(lock) = self.lock.take() else {
837 return Ok(());
838 };
839 let discard = discard_path(&self.path);
840 let (removed, at) = if publish_no_replace(&self.path, &discard, &RetryPolicy::NONE).is_ok()
841 {
842 close_lock(lock, &discard);
843 let keep_trying = || true;
844 let retry = RetryPolicy {
845 budget: PUBLISH_RETRY_BUDGET,
846 on_wait: &keep_trying,
847 };
848 let removed =
849 alpha2_os::with_publish_retries(&retry, || fs::remove_file(&discard)).map(|_| ());
850 (removed, discard)
851 } else {
852 let removed = fs::remove_file(&self.path);
853 close_lock(lock, &self.path);
854 (removed, self.path.clone())
855 };
856 match removed {
857 Ok(()) => Ok(()),
858 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
859 Err(error) => Err(output_error_at(&at, error)),
860 }
861 }
862}
863
864impl Drop for PartialOutput {
865 fn drop(&mut self) {
866 let _ = self.discard();
867 }
868}
869
870fn close_lock(lock: File, name: &Path) {
872 drop(lock);
873 hooks::lock_closed(name);
874}
875
876fn rewrite_at_start(file: &mut File) -> std::io::Result<()> {
878 file.write_all(&[0, 0])?;
879 file.seek(SeekFrom::Start(0))?;
880 file.write_all(&[1])?;
881 file.sync_all()
882}
883
884fn cannot_seek(error: &std::io::Error) -> bool {
887 matches!(
888 error.kind(),
889 std::io::ErrorKind::NotSeekable
890 | std::io::ErrorKind::InvalidInput
891 | std::io::ErrorKind::Unsupported
892 )
893}
894
895fn create_staging(final_path: &Path) -> Result<PathBuf, EncodeError> {
897 let extension = final_path
898 .extension()
899 .and_then(|extension| extension.to_str())
900 .unwrap_or("bin");
901 for _ in 0..CLAIM_ATTEMPTS {
902 let n = NEXT_SCRATCH.fetch_add(1, Ordering::Relaxed);
903 let staging = std::env::temp_dir().join(format!(
904 "alpha2-staging-{}-{n}.{extension}",
905 std::process::id()
906 ));
907 match OpenOptions::new()
908 .write(true)
909 .create_new(true)
910 .open(&staging)
911 {
912 Ok(_) => return Ok(staging),
913 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
914 Err(error) => return Err(output_error_at(&staging, error)),
915 }
916 }
917 Err(EncodeError::Output(
918 "no staging file could be created in the temporary directory".into(),
919 ))
920}
921
922#[cfg(windows)]
924fn warn_if_held(final_path: &Path) {
925 use std::os::windows::fs::OpenOptionsExt;
926 const DELETE: u32 = 0x0001_0000;
927 const SHARE_READ_WRITE_DELETE: u32 = 0x1 | 0x2 | 0x4;
928 const ERROR_SHARING_VIOLATION: i32 = 32;
929 if let Err(error) = OpenOptions::new()
930 .access_mode(DELETE)
931 .share_mode(SHARE_READ_WRITE_DELETE)
932 .open(final_path)
933 && error.raw_os_error() == Some(ERROR_SHARING_VIOLATION)
934 {
935 alpha2_os::diagnostic!(
936 "alpha2: {} is open in another program; the export will wait up to {} s for it when it finishes",
937 final_path.display(),
938 PUBLISH_RETRY_BUDGET.as_secs()
939 );
940 }
941}
942
943fn publish_no_replace(
945 from: &Path,
946 to: &Path,
947 retry: &RetryPolicy<'_>,
948) -> std::io::Result<Published> {
949 if let Some(error) = hooks::publish_failure(to) {
950 return Err(error);
951 }
952 alpha2_os::publish_no_replace(from, to, retry)
953}
954
955#[cfg(unix)]
957fn sync_directory(dir: &Path) -> std::io::Result<()> {
958 alpha2_os::sync_directory(dir)?;
959 hooks::record("directory sync");
960 Ok(())
961}
962
963fn replaceable(final_path: &Path) -> Result<(), String> {
966 match fs::symlink_metadata(final_path) {
967 Ok(metadata) if metadata.file_type().is_file() => Ok(()),
968 Ok(_) => Err(format!(
969 "refusing to replace {}: not a regular file",
970 final_path.display()
971 )),
972 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
973 Err(error) => Err(format!("{}: {error}", final_path.display())),
974 }
975}
976
977pub fn write_whole(
986 target: impl Into<OutputTarget>,
987 write: impl FnOnce(&mut File) -> Result<(), String>,
988) -> Result<PublishReport, EncodeError> {
989 let target = target.into();
990 let mut partial = PartialOutput::claim(&target, SeekNeed::NotNeeded)?;
991 let mut file = partial.open_file()?;
992 write(&mut file).map_err(|error| output_error_at(partial.write_path(), error))?;
993 drop(file);
994 partial.finish(&CancelToken::default())
995}
996
997pub fn write_png(
1003 target: impl Into<OutputTarget>,
1004 width: u32,
1005 height: u32,
1006 rgba: &[u8],
1007) -> Result<PublishReport, EncodeError> {
1008 let expected = u64::from(width) * u64::from(height) * 4;
1009 if u64::try_from(rgba.len()).ok() != Some(expected) {
1010 return Err(EncodeError::Adapter(format!(
1011 "a {width}x{height} RGBA image is {expected} bytes, not {}",
1012 rgba.len()
1013 )));
1014 }
1015 write_whole(target, |file| {
1016 let mut buffered = std::io::BufWriter::new(file);
1017 encode_png(&mut buffered, width, height, rgba)?;
1018 buffered
1019 .into_inner()
1020 .map(|_| ())
1021 .map_err(|error| error.error().to_string())
1022 })
1023}
1024
1025pub fn png_bytes(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
1030 let expected = u64::from(width) * u64::from(height) * 4;
1031 if u64::try_from(rgba.len()).ok() != Some(expected) {
1032 return Err(format!(
1033 "a {width}x{height} RGBA image is {expected} bytes, not {}",
1034 rgba.len()
1035 ));
1036 }
1037 let mut bytes = Vec::new();
1038 encode_png(&mut bytes, width, height, rgba)?;
1039 Ok(bytes)
1040}
1041
1042fn encode_png(
1043 output: &mut impl std::io::Write,
1044 width: u32,
1045 height: u32,
1046 rgba: &[u8],
1047) -> Result<(), String> {
1048 let mut encoder = png::Encoder::new(output, width, height);
1049 encoder.set_color(png::ColorType::Rgba);
1050 encoder.set_depth(png::BitDepth::Eight);
1051 encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
1053 let mut writer = encoder.write_header().map_err(|error| error.to_string())?;
1054 writer
1055 .write_image_data(rgba)
1056 .map_err(|error| error.to_string())?;
1057 writer.finish().map_err(|error| error.to_string())
1058}
1059
1060pub fn remove_stale_partial_output(path: impl AsRef<Path>) -> Result<bool, EncodeError> {
1068 let partial = partial_output_path(path.as_ref())?;
1069 let Some((file, _)) = lock_partial(&partial, false, &mut alpha2_os::try_lock_exclusive)? else {
1070 return Ok(false);
1071 };
1072 let removed = fs::remove_file(&partial);
1073 drop(file);
1074 match removed {
1075 Ok(()) => Ok(true),
1076 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
1077 Err(error) => Err(output_error(error)),
1078 }
1079}
1080
1081#[cfg(not(any(test, feature = "test-hooks")))]
1083mod hooks {
1084 use std::path::Path;
1085
1086 pub(super) fn publish_failure(_to: &Path) -> Option<std::io::Error> {
1087 None
1088 }
1089
1090 pub(super) fn not_seekable() -> bool {
1091 false
1092 }
1093
1094 pub(super) fn record(_event: &'static str) {}
1095
1096 pub(super) fn lock_closed(_name: &Path) {}
1097
1098 pub(super) const fn periodic_sync_bytes(_path: &Path) -> u64 {
1099 super::PERIODIC_SYNC_BYTES
1100 }
1101
1102 pub(super) const fn sync_delay(_path: &Path, _bytes: u64) {}
1103}
1104
1105#[cfg(any(test, feature = "test-hooks"))]
1107#[allow(missing_docs)]
1108pub mod hooks {
1109 use std::cell::{Cell, RefCell};
1110 use std::path::{Path, PathBuf};
1111
1112 pub type LockCloseHook = Box<dyn Fn(&Path)>;
1114
1115 thread_local! {
1116 pub static FAIL_PUBLISH_TO: RefCell<Option<(PathBuf, i32)>> =
1118 const { RefCell::new(None) };
1119 pub static NOT_SEEKABLE: Cell<bool> = const { Cell::new(false) };
1121 pub static EVENTS: RefCell<Option<Vec<&'static str>>> =
1123 const { RefCell::new(None) };
1124 pub static ON_LOCK_CLOSE: RefCell<Option<LockCloseHook>> =
1126 const { RefCell::new(None) };
1127 }
1128
1129 pub(super) fn publish_failure(to: &Path) -> Option<std::io::Error> {
1130 FAIL_PUBLISH_TO.with_borrow(|fail| {
1131 fail.as_ref()
1132 .filter(|(path, _)| path == to)
1133 .map(|(_, code)| std::io::Error::from_raw_os_error(*code))
1134 })
1135 }
1136
1137 pub(super) fn not_seekable() -> bool {
1138 NOT_SEEKABLE.get()
1139 }
1140
1141 pub(super) fn record(event: &'static str) {
1142 EVENTS.with_borrow_mut(|events| {
1143 if let Some(events) = events {
1144 events.push(event);
1145 }
1146 });
1147 }
1148
1149 pub(super) fn lock_closed(name: &Path) {
1150 ON_LOCK_CLOSE.with_borrow(|hook| {
1151 if let Some(hook) = hook {
1152 hook(name);
1153 }
1154 });
1155 }
1156
1157 pub static SLOW_SYNC: std::sync::Mutex<Option<(PathBuf, u64, u64)>> =
1160 std::sync::Mutex::new(None);
1161
1162 fn slow_sync(path: &Path) -> Option<(u64, u64)> {
1163 SLOW_SYNC
1164 .lock()
1165 .unwrap_or_else(std::sync::PoisonError::into_inner)
1166 .as_ref()
1167 .filter(|(slow, _, _)| slow == path)
1168 .map(|&(_, interval, nanos)| (interval, nanos))
1169 }
1170
1171 pub(super) fn periodic_sync_bytes(path: &Path) -> u64 {
1172 slow_sync(path).map_or(super::PERIODIC_SYNC_BYTES, |(interval, _)| interval)
1173 }
1174
1175 pub(super) fn sync_delay(path: &Path, bytes: u64) {
1176 if let Some((_, nanos)) = slow_sync(path) {
1177 std::thread::sleep(std::time::Duration::from_nanos(
1178 nanos.saturating_mul(bytes / 1024),
1179 ));
1180 }
1181 }
1182}
1183
1184#[cfg(test)]
1185mod tests {
1186 use std::cell::RefCell;
1187 use std::io::{Read, Write};
1188
1189 use super::*;
1190
1191 #[test]
1192 fn an_output_is_synced_while_it_is_written_and_the_final_sync_covers_the_rest() {
1193 let path = final_path("periodic-sync");
1194 *hooks::SLOW_SYNC.lock().expect("hook") = Some((path.clone(), 1 << 20, 0));
1195 hooks::EVENTS.set(Some(Vec::new()));
1196 let mut partial =
1197 PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1198 let mut file = partial.open_file().expect("open");
1199 let chunk = vec![7_u8; 64 << 10];
1200 for _ in 0..56 {
1201 file.write_all(&chunk).expect("write");
1202 partial.wrote(64 << 10).expect("periodic sync");
1203 }
1204 drop(file);
1205 partial.finish(&CancelToken::default()).expect("publish");
1206 let events = hooks::EVENTS.take().expect("events");
1207 *hooks::SLOW_SYNC.lock().expect("hook") = None;
1208 let mut expected = vec!["periodic sync"; 3];
1209 expected.extend(["sync", "rename"]);
1210 if cfg!(unix) {
1211 expected.push("directory sync");
1212 }
1213 assert_eq!(events, expected);
1214 assert_eq!(fs::metadata(&path).expect("published").len(), 56 << 16);
1215 fs::remove_file(&path).ok();
1216 }
1217
1218 #[test]
1219 fn a_cancel_during_the_staging_copy_publishes_nothing_and_removes_both_files() {
1220 let path = final_path("staged-cancel");
1221 hooks::NOT_SEEKABLE.set(true);
1222 let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required);
1223 hooks::NOT_SEEKABLE.set(false);
1224 let mut partial = claimed.expect("claim");
1225 let staging = partial.write_path().to_owned();
1226 assert_ne!(staging, partial.path, "the output was not staged");
1227 let mut writer = partial.open_file().expect("the staging file opens");
1228 writer
1229 .write_all(&vec![7_u8; 3 * STAGING_COPY_CHUNK])
1230 .expect("three chunks");
1231 drop(writer);
1232 let cancel = CancelToken::default();
1233 let beats = std::cell::Cell::new(0);
1234 let watched = cancel.clone();
1235 let _watch = crate::encode_watch::watch_encode_calls(move || {
1237 beats.set(beats.get() + 1);
1238 if beats.get() == 2 {
1239 watched.cancel();
1240 }
1241 });
1242 assert!(matches!(
1243 partial.finish(&cancel),
1244 Err(EncodeError::Cancelled)
1245 ));
1246 assert!(!path.exists(), "the cancelled copy was published");
1247 assert!(!partial.path.exists(), "the partial was left");
1248 assert!(!staging.exists(), "the staging file was left");
1249 }
1250
1251 fn final_path(label: &str) -> PathBuf {
1253 let path =
1254 std::env::temp_dir().join(format!("alpha2-claim-{label}-{}.mp4", std::process::id()));
1255 let _ = fs::remove_file(&path);
1256 let _ = fs::remove_file(partial_output_path(&path).expect("partial path"));
1257 path
1258 }
1259
1260 fn no_locks(_: &File) -> std::io::Result<bool> {
1262 Err(std::io::Error::other("No locks available"))
1263 }
1264
1265 #[test]
1266 fn a_partial_the_claim_created_and_could_not_lock_is_removed() {
1267 let path = final_path("unlockable");
1268 let partial = partial_output_path(&path).expect("partial path");
1269 let Err(error) =
1270 PartialOutput::claim_partial_locking(&OutputTarget::from(&path), &mut no_locks)
1271 else {
1272 panic!("a claim without a lock succeeded");
1273 };
1274 assert!(
1275 matches!(&error, EncodeError::Output(message) if message.contains(&partial.display().to_string())),
1276 "{error}"
1277 );
1278 assert!(
1279 !partial.exists(),
1280 "the refused claim left the partial it created"
1281 );
1282 }
1283
1284 #[test]
1285 fn a_partial_that_was_there_is_left_when_the_lock_fails() {
1286 let path = final_path("unlockable-existing");
1287 let partial = partial_output_path(&path).expect("partial path");
1288 fs::write(&partial, b"another export's").expect("existing partial");
1289 assert!(
1290 PartialOutput::claim_partial_locking(&OutputTarget::from(&path), &mut no_locks)
1291 .is_err()
1292 );
1293 assert_eq!(
1294 fs::read(&partial).expect("still there"),
1295 b"another export's"
1296 );
1297 fs::remove_file(&partial).expect("clean up");
1298 }
1299
1300 #[test]
1301 fn a_partial_its_holder_removes_while_it_is_claimed_is_claimed_new() {
1302 let path = final_path("removed-while-claimed");
1305 let partial = partial_output_path(&path).expect("partial path");
1306 let target = OutputTarget::from(&path);
1307 let mut holder = Some(PartialOutput::claim(&target, SeekNeed::Required).expect("holder"));
1308 let claimed = PartialOutput::claim_partial_locking(&target, &mut |file| {
1309 drop(holder.take());
1310 alpha2_os::try_lock_exclusive(file)
1311 })
1312 .expect("claimed after the holder finished");
1313 assert!(holder.is_none());
1314 let mut writer = claimed.open_file().expect("the claimed partial opens");
1315 writer.write_all(b"new export").expect("write");
1316 drop(writer);
1317 let mut read = String::new();
1318 File::open(&partial)
1319 .and_then(|mut file| file.read_to_string(&mut read))
1320 .expect("read back");
1321 assert_eq!(read, "new export");
1322 drop(claimed);
1323 assert!(!partial.exists());
1324 }
1325
1326 #[test]
1327 fn a_stale_partial_is_replaced_not_emptied() {
1328 let path = final_path("stale-replaced");
1329 let partial = partial_output_path(&path).expect("partial path");
1330 fs::write(&partial, b"what a killed export left").expect("stale partial");
1331 let stale = File::open(&partial).expect("the stale file");
1332 let claimed =
1333 PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1334 assert!(
1335 !alpha2_os::same_file(&stale, &partial).expect("identity"),
1336 "the stale file was reused"
1337 );
1338 let mut bytes = Vec::new();
1339 (&stale)
1340 .read_to_end(&mut bytes)
1341 .expect("read the stale file");
1342 assert_eq!(
1343 bytes, b"what a killed export left",
1344 "the stale file was emptied"
1345 );
1346 assert_eq!(fs::read(&partial).expect("new partial"), b"");
1347 drop(claimed);
1348 assert!(!partial.exists());
1349 }
1350
1351 #[test]
1352 #[cfg(unix)]
1353 fn a_stale_partial_that_is_a_second_name_of_the_output_leaves_the_output_intact() {
1354 let path = final_path("stale-second-name");
1355 let partial = partial_output_path(&path).expect("partial path");
1356 fs::write(&path, b"the published output").expect("output");
1357 fs::hard_link(&path, &partial).expect("second name");
1358 let claimed = PartialOutput::claim(&OutputTarget::replacing(&path), SeekNeed::Required)
1359 .expect("claim");
1360 assert_eq!(
1361 fs::read(&path).expect("output"),
1362 b"the published output",
1363 "claiming the partial changed the output"
1364 );
1365 assert!(!alpha2_os::same_file_at(&path, &partial).expect("identity"));
1366 drop(claimed);
1367 assert!(!partial.exists());
1368 assert_eq!(fs::read(&path).expect("output"), b"the published output");
1369 fs::remove_file(&path).expect("clean up");
1370 }
1371
1372 #[test]
1373 fn a_held_partial_is_refused_after_a_short_wait() {
1374 let path = final_path("held-refused");
1375 let target = OutputTarget::from(&path);
1376 let held = PartialOutput::claim(&target, SeekNeed::Required).expect("holder");
1377 let started = Instant::now();
1378 let refused = PartialOutput::claim(&target, SeekNeed::Required);
1379 let waited = started.elapsed();
1380 assert!(
1381 matches!(&refused, Err(EncodeError::OutputInUse(message)) if message.starts_with(PARTIAL_OUTPUT_IN_USE)),
1382 "{:?}",
1383 refused.err()
1384 );
1385 assert!(waited >= CLAIM_IN_USE_WAIT, "refused after {waited:?}");
1386 drop(held);
1387 }
1388
1389 #[test]
1390 fn a_partial_released_within_the_wait_is_claimed() {
1391 let path = final_path("held-released");
1392 let partial = partial_output_path(&path).expect("partial path");
1393 let holder = OpenOptions::new()
1394 .read(true)
1395 .write(true)
1396 .create_new(true)
1397 .open(&partial)
1398 .expect("holder's partial");
1399 assert!(alpha2_os::try_lock_exclusive(&holder).expect("holder's lock"));
1400 let released = std::thread::spawn(move || {
1401 std::thread::sleep(Duration::from_millis(50));
1402 drop(holder);
1403 });
1404 let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required)
1405 .expect("claimed once the holder let go");
1406 released.join().expect("holder");
1407 drop(claimed);
1408 assert!(!partial.exists());
1409 }
1410
1411 #[test]
1412 #[cfg(windows)]
1413 fn a_partial_another_program_holds_open_briefly_is_claimed() {
1414 use std::os::windows::fs::OpenOptionsExt;
1415 const FILE_SHARE_READ: u32 = 1;
1416 const FILE_SHARE_WRITE: u32 = 2;
1417 for share in [FILE_SHARE_READ, FILE_SHARE_READ | FILE_SHARE_WRITE] {
1418 let path = final_path(&format!("held-open-{share}"));
1419 let partial = partial_output_path(&path).expect("partial path");
1420 fs::write(&partial, b"").expect("partial");
1421 let reader = OpenOptions::new()
1422 .read(true)
1423 .share_mode(share)
1424 .open(&partial)
1425 .expect("reader");
1426 let released = std::thread::spawn(move || {
1427 std::thread::sleep(Duration::from_millis(300));
1428 drop(reader);
1429 });
1430 let claimed = PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required)
1431 .unwrap_or_else(|error| panic!("share {share}: {error}"));
1432 released.join().expect("reader");
1433 drop(claimed);
1434 assert!(!partial.exists(), "share {share}");
1435 }
1436 }
1437
1438 #[test]
1439 fn a_name_near_the_limit_gets_a_shortened_partial_name() {
1440 let directory = std::env::temp_dir();
1441 let limit = alpha2_os::name_limit(&directory);
1442 let syllables = match limit.unit {
1446 alpha2_os::NameUnit::Bytes => 81,
1447 alpha2_os::NameUnit::Utf16 => 243,
1448 };
1449 let name = format!("{}.mp4", "\u{d55c}".repeat(syllables));
1450 assert_eq!(limit.length(&name), 247);
1451 let path = directory.join(&name);
1452 let _ = fs::remove_file(&path);
1453 let partial = partial_output_path(&path).expect("partial path");
1454 assert_eq!(
1455 partial,
1456 partial_output_path(&path).expect("again"),
1457 "deterministic"
1458 );
1459 let siblings = [
1460 partial.clone(),
1461 sibling_path(&path, &kept_tag(1)).expect("kept"),
1462 sibling_path(&path, &kept_tag(KEPT_NAMES)).expect("last kept"),
1463 sibling_path(&path, TAG_PROBE[0]).expect("probe"),
1464 sibling_path(&path, TAG_PROBE[1]).expect("probe"),
1465 ];
1466 for sibling in &siblings {
1467 let sibling_name = sibling
1468 .file_name()
1469 .and_then(|name| name.to_str())
1470 .expect("name");
1471 assert!(
1472 limit.length(sibling_name) <= limit.max.min(255),
1473 "{sibling_name} is {} long",
1474 limit.length(sibling_name)
1475 );
1476 assert!(sibling_name.contains('~'), "{sibling_name}");
1477 }
1478 let partial_name = partial
1479 .file_name()
1480 .and_then(|name| name.to_str())
1481 .expect("name");
1482 assert!(partial_name.starts_with('\u{d55c}'), "{partial_name}");
1483 assert!(partial_name.ends_with(".a2partial.mp4"), "{partial_name}");
1484
1485 let mut claimed =
1486 PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1487 assert!(partial.exists());
1488 drop(claimed.lock.take());
1490 claimed.state = PartialState::Kept;
1491 drop(claimed);
1492 assert!(remove_stale_partial_output(&path).expect("stale partial"));
1493 assert!(!partial.exists());
1494
1495 let short = directory.join("short.mp4");
1496 assert_eq!(
1497 partial_output_path(&short).expect("partial path"),
1498 directory.join("short.a2partial.mp4")
1499 );
1500 }
1501
1502 #[test]
1503 fn a_discarded_partial_leaves_nothing_even_when_its_name_is_recreated_on_close() {
1504 let path = final_path("recreated-on-close");
1506 let partial = partial_output_path(&path).expect("partial path");
1507 let closed_as = std::rc::Rc::new(RefCell::new(None));
1508 let record = std::rc::Rc::clone(&closed_as);
1509 hooks::ON_LOCK_CLOSE.set(Some(Box::new(move |name: &Path| {
1510 fs::write(name, b"written back").expect("write back");
1511 *record.borrow_mut() = Some(name.to_owned());
1512 })));
1513 let claimed =
1514 PartialOutput::claim(&OutputTarget::from(&path), SeekNeed::Required).expect("claim");
1515 drop(claimed);
1516 hooks::ON_LOCK_CLOSE.set(None);
1517 let closed_as = closed_as.borrow().clone().expect("the lock closed");
1518 assert_ne!(
1519 closed_as, partial,
1520 "the lock closed under the partial's name"
1521 );
1522 assert!(!partial.exists(), "the partial name came back");
1523 assert!(
1524 !closed_as.exists(),
1525 "the written-back discard name was left"
1526 );
1527 }
1528}