Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
refactor(recording): add finalize path distinct from crash recovery
Richie McIlroy4a552e59d6a1
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rsindex 366009f2d..e542718b0 100644--- a/crates/recording/src/recovery.rs+++ b/crates/recording/src/recovery.rs@@ -15,10 +15,16 @@ use cap_project::{TimelineSegment, VideoMeta,};use relative_path::RelativePathBuf;-use tracing::{debug, info, warn};+use tracing::{debug, warn};use crate::output_pipeline::{HealthSender, PipelineHealthEvent, emit_health};+macro_rules! finalization_info {+ ($($arg:tt)*) => {+ tracing::info!(target: "cap_recording::recording_finalization", $($arg)*)+ };+}+#[derive(Debug, Clone)]pub struct IncompleteRecording {pub project_path: PathBuf,@@ -51,6 +57,35 @@ struct FragmentsInfo {init_segment: Option<PathBuf>,}+#[derive(Debug, Clone, Copy)]+enum RecoveryPurpose {+ Recover,+ Finalize,+}++impl RecoveryPurpose {+ fn success_message(self) -> &'static str {+ match self {+ Self::Recover => "Successfully recovered recording",+ Self::Finalize => "Successfully finalized fragmented recording",+ }+ }++ fn timeline_message(self) -> &'static str {+ match self {+ Self::Recover => "Created project configuration with timeline for recovered recording",+ Self::Finalize => "Created project configuration with timeline for finalized recording",+ }+ }++ fn track_action(self) -> &'static str {+ match self {+ Self::Recover => "recovery",+ Self::Finalize => "finalization",+ }+ }+}+#[derive(Debug, thiserror::Error)]pub enum RecoveryError {#[error("IO error: {0}")]@@ -110,10 +145,6 @@ impl RecoveryManager {}}- /// Remux a recording in place if its tracks are still fragment directories (status `NeedsRemux`,- /// e.g. straight after a fragmented studio stop), running the same `recover` the desktop uses- /// after stop. A no-op for recordings already stored as progressive mp4, so callers can run it- /// unconditionally before consuming a `.cap`.pub fn remux_if_needed(project_path: &Path) -> Result<bool, RecoveryError> {let Some(incomplete) = Self::find_incomplete_single(project_path) else {return Ok(false);@@ -123,7 +154,7 @@ impl RecoveryManager {return Ok(false);}- Self::recover(&incomplete)?;+ Self::finalize(&incomplete)?;Ok(true)}@@ -168,8 +199,7 @@ impl RecoveryManager {fn should_check_for_recovery(status: &StudioRecordingStatus) -> bool {match status {StudioRecordingStatus::InProgress | StudioRecordingStatus::NeedsRemux => true,- StudioRecordingStatus::Failed { error } => error != "No recoverable segments found",- StudioRecordingStatus::Complete => false,+ StudioRecordingStatus::Failed { .. } | StudioRecordingStatus::Complete => false,}}@@ -267,12 +297,12 @@ impl RecoveryManager {}if recoverable_segments.is_empty() {- info!("No recoverable segments found in {:?}", project_path);+ finalization_info!("No fragmented segments found in {:?}", project_path);return None;}- info!(- "Found {} recoverable segments in {:?} with estimated duration {:?}",+ finalization_info!(+ "Found {} fragmented segments in {:?} with estimated duration {:?}",recoverable_segments.len(),project_path,total_duration@@ -503,7 +533,7 @@ impl RecoveryManager {indexed.sort_by_key(|(idx, _)| *idx);- info!(+ finalization_info!("Including {} fragments from respawn-{} at {}",indexed.len(),n,@@ -586,7 +616,7 @@ impl RecoveryManager {}match std::fs::rename(&path, &final_path) {Ok(()) => {- info!(+ finalization_info!("Rescued in-progress tmp fragment: {} -> {} ({} bytes)",path.display(),final_path.display(),@@ -728,6 +758,17 @@ impl RecoveryManager {}pub fn recover(recording: &IncompleteRecording) -> Result<RecoveredRecording, RecoveryError> {+ Self::finalize_with_purpose(recording, RecoveryPurpose::Recover)+ }++ pub fn finalize(recording: &IncompleteRecording) -> Result<RecoveredRecording, RecoveryError> {+ Self::finalize_with_purpose(recording, RecoveryPurpose::Finalize)+ }++ fn finalize_with_purpose(+ recording: &IncompleteRecording,+ purpose: RecoveryPurpose,+ ) -> Result<RecoveredRecording, RecoveryError> {if recording.recoverable_segments.is_empty() {return Err(RecoveryError::NoRecoverableSegments);}@@ -744,7 +785,7 @@ impl RecoveryManager {if segment.display_fragments.len() == 1 && segment.display_init_segment.is_none() {let source = &segment.display_fragments[0];if source != &display_output {- info!("Moving single display fragment to {:?}", display_output);+ finalization_info!("Moving single display fragment to {:?}", display_output);std::fs::rename(source, &display_output)?;}Self::validate_required_video(&display_output, "display")?;@@ -794,7 +835,7 @@ impl RecoveryManager {if camera_frags.len() == 1 && segment.camera_init_segment.is_none() {let source = &camera_frags[0];if source != &camera_output {- info!("Moving single camera fragment to {:?}", camera_output);+ finalization_info!("Moving single camera fragment to {:?}", camera_output);std::fs::rename(source, &camera_output)?;}match Self::validate_required_video(&camera_output, "camera") {@@ -828,7 +869,8 @@ impl RecoveryManager {Ok(()) => true,Err(err) => {warn!(- "Camera track recovery failed for {:?}: {err}. Preserving fragments for retry.",+ "Camera track {} failed for {:?}: {err}. Preserving fragments for retry.",+ purpose.track_action(),camera_output);if let Err(e) = std::fs::remove_file(&camera_output)@@ -870,10 +912,13 @@ impl RecoveryManager {let is_ogg = source.extension().map(|e| e == "ogg").unwrap_or(false);if source != &mic_output {if is_ogg {- info!("Moving single mic fragment to {:?}", mic_output);+ finalization_info!("Moving single mic fragment to {:?}", mic_output);std::fs::rename(source, &mic_output)?;} else {- info!("Transcoding single mic fragment to {:?}", mic_output);+ finalization_info!(+ "Transcoding single mic fragment to {:?}",+ mic_output+ );concatenate_audio_to_ogg(mic_frags, &mic_output).map_err(RecoveryError::AudioConcat)?;if let Err(e) = std::fs::remove_file(source) {@@ -888,7 +933,7 @@ impl RecoveryManager {}}} else if mic_frags.len() > 1 {- info!(+ finalization_info!("Concatenating {} mic fragments to {:?}",mic_frags.len(),mic_output@@ -917,10 +962,13 @@ impl RecoveryManager {let is_ogg = source.extension().map(|e| e == "ogg").unwrap_or(false);if source != &system_output {if is_ogg {- info!("Moving single system audio fragment to {:?}", system_output);+ finalization_info!(+ "Moving single system audio fragment to {:?}",+ system_output+ );std::fs::rename(source, &system_output)?;} else {- info!(+ finalization_info!("Transcoding single system audio fragment to {:?}",system_output);@@ -938,7 +986,7 @@ impl RecoveryManager {}}} else if system_frags.len() > 1 {- info!(+ finalization_info!("Concatenating {} system audio fragments to {:?}",system_frags.len(),system_output@@ -969,10 +1017,11 @@ impl RecoveryManager {.save_for_project().map_err(|_| RecoveryError::MetaSave)?;- Self::create_project_config(recording, &meta)?;+ Self::create_project_config(recording, &meta, purpose)?;- info!(- "Successfully recovered recording at {:?}",+ finalization_info!(+ "{} at {:?}",+ purpose.success_message(),recording.project_path);@@ -1131,7 +1180,7 @@ impl RecoveryManager {}if let Some(init_path) = init_segment {- info!(+ finalization_info!("Concatenating {} M4S {label} segments with init to {:?}",fragments.len(),output@@ -1139,7 +1188,7 @@ impl RecoveryManager {concatenate_m4s_segments_with_init(init_path, fragments, output).map_err(RecoveryError::VideoConcat)?;} else {- info!(+ finalization_info!("Concatenating {} {label} fragments to {:?}",fragments.len(),output@@ -1162,7 +1211,7 @@ impl RecoveryManager {}if let Some(init_path) = init_segment {- info!(+ finalization_info!("Concatenating {} M4S {label} segments with init to {:?}",fragments.len(),output@@ -1170,7 +1219,7 @@ impl RecoveryManager {concatenate_m4s_segments_with_init(init_path, fragments, output).map_err(RecoveryError::AudioConcat)?;} else {- info!(+ finalization_info!("Concatenating {} {label} fragments to {:?}",fragments.len(),output@@ -1182,14 +1231,15 @@ impl RecoveryManager {}fn validate_required_video(path: &Path, label: &str) -> Result<(), RecoveryError> {- info!("Validating recovered {} video: {:?}", label, path);+ finalization_info!("Validating finalized {} video: {:?}", label, path);Self::ensure_video_decodes(path, label)?;if let Err(seek_error) = probe_video_seek_points(path, EXPORT_SEEK_PROBE_SAMPLE_COUNT) {- info!(- "Recovered {} video failed seek validation, normalizing via remux: {}",- label, seek_error+ finalization_info!(+ "Finalized {} video failed seek validation, normalizing via remux: {}",+ label,+ seek_error);Self::normalize_recovered_video(path, label)?;}@@ -1224,8 +1274,8 @@ impl RecoveryManager {))})?;- info!(- "Recovered {} video validation passed after normalization",+ finalization_info!(+ "Finalized {} video validation passed after normalization",label);@@ -1378,6 +1428,7 @@ impl RecoveryManager {fn create_project_config(recording: &IncompleteRecording,meta: &StudioRecordingMeta,+ purpose: RecoveryPurpose,) -> Result<(), RecoveryError> {let StudioRecordingMeta::MultipleSegments { inner, .. } = meta else {return Ok(());@@ -1438,7 +1489,7 @@ impl RecoveryManager {.write(&recording.project_path).map_err(RecoveryError::Io)?;- info!("Created project configuration with timeline for recovered recording");+ finalization_info!("{}", purpose.timeline_message());Ok(())}@@ -1484,8 +1535,8 @@ impl RecoveryManager {},);- info!(- "Recovered cursor {} from image file: {:?}",+ finalization_info!(+ "Loaded cursor {} from image file: {:?}",id_str,path.file_name());@@ -1528,6 +1579,14 @@ impl RecoveryManager {let status_updated = match &mut updated_meta.inner {RecordingMetaInner::Studio(studio) => {if let StudioRecordingMeta::MultipleSegments { inner, .. } = studio.as_mut() {+ if matches!(inner.status, Some(StudioRecordingStatus::Failed { .. })) {+ debug!(+ "Recording already failed before startup cleanup, preserving original status: {:?}",+ project_path+ );+ return;+ }+inner.status = Some(StudioRecordingStatus::Failed {error: "No recoverable segments found".to_string(),});@@ -1546,8 +1605,8 @@ impl RecoveryManager {project_path, e);} else {- info!(- "Marked recording as unrecoverable (no recoverable segments): {:?}",+ debug!(+ "Marked stale recording as failed because no media fragments were present: {:?}",project_path);}diff --git a/crates/recording/tests/recovery.rs b/crates/recording/tests/recovery.rsindex dec50c9c7..05154ffdd 100644--- a/crates/recording/tests/recovery.rs+++ b/crates/recording/tests/recovery.rs@@ -109,9 +109,16 @@ impl TestRecording {}fn write_recording_meta(&self, status: StudioRecordingStatus) -> std::io::Result<()> {+ Self::write_recording_meta_at(&self.project_path, status)+ }++ fn write_recording_meta_at(+ project_path: &Path,+ status: StudioRecordingStatus,+ ) -> std::io::Result<()> {let meta = RecordingMeta {platform: None,- project_path: self.project_path.clone(),+ project_path: project_path.to_path_buf(),pretty_name: "Test Recording".to_string(),sharing: None,upload: None,@@ -136,7 +143,7 @@ impl TestRecording {})),};- let meta_path = self.project_path.join("recording-meta.json");+ let meta_path = project_path.join("recording-meta.json");std::fs::write(meta_path, serde_json::to_string_pretty(&meta)?)?;Ok(())}@@ -476,26 +483,34 @@ fn test_should_not_check_for_recovery_complete() {}#[test]-fn test_should_check_for_recovery_failed_with_other_error() {+fn test_failed_recording_is_terminal_for_startup_recovery() {test_utils::init_tracing();let recording = TestRecording::new().unwrap();+ let display_dir = recording.create_display_dir(0).unwrap();+ recording+ .write_manifest(+ 0,+ "display",+ &[("segment_001.m4s", true, 150)],+ Some("init.mp4"),+ )+ .unwrap();+ std::fs::write(display_dir.join("init.mp4"), create_minimal_mp4_data()).unwrap();+ std::fs::write(display_dir.join("segment_001.m4s"), vec![1u8; 150]).unwrap();recording.write_recording_meta(StudioRecordingStatus::Failed {error: "Some other error".to_string(),}).unwrap();- let meta = RecordingMeta::load_for_project(recording.path()).unwrap();- let studio_meta = meta.studio_meta().unwrap();- let status = studio_meta.status();+ let inspected = RecoveryManager::inspect_recording(recording.path()).unwrap();+ assert_eq!(inspected.recoverable_segments.len(), 1);- match status {- StudioRecordingStatus::Failed { error } => {- assert_eq!(error, "Some other error");- }- _ => panic!("Status should be Failed"),- }+ assert!(+ RecoveryManager::find_incomplete_single(recording.path()).is_none(),+ "Failed recordings should not be startup recovery candidates"+ );}#[test]@@ -538,6 +553,39 @@ fn test_find_incomplete_with_no_segments_directory() {);}+#[test]+fn test_find_incomplete_preserves_failed_error_without_segments() {+ test_utils::init_tracing();++ let recordings_dir = TempDir::new().unwrap();+ let project_path = recordings_dir.path().join("failed-start.cap");+ std::fs::create_dir_all(&project_path).unwrap();+ let original_error =+ "RefreshShareableContent: The user declined TCCs for application, window, display capture";++ TestRecording::write_recording_meta_at(+ &project_path,+ StudioRecordingStatus::Failed {+ error: original_error.to_string(),+ },+ )+ .unwrap();++ let incomplete = RecoveryManager::find_incomplete(recordings_dir.path());++ assert!(+ incomplete.is_empty(),+ "Should not find incomplete recordings without segments directory"+ );++ let meta = RecordingMeta::load_for_project(&project_path).unwrap();+ let studio_meta = meta.studio_meta().unwrap();+ match studio_meta.status() {+ StudioRecordingStatus::Failed { error } => assert_eq!(error, original_error),+ _ => panic!("Status should preserve original failed-start error"),+ }+}+#[test]fn test_find_incomplete_with_empty_segments_directory() {test_utils::init_tracing();@@ -1047,8 +1095,7 @@ fn test_status_transition_logic() {let should_check = |status: &StudioRecordingStatus| -> bool {match status {StudioRecordingStatus::InProgress | StudioRecordingStatus::NeedsRemux => true,- StudioRecordingStatus::Failed { error } => error != "No recoverable segments found",- StudioRecordingStatus::Complete => false,+ StudioRecordingStatus::Failed { .. } | StudioRecordingStatus::Complete => false,}};@@ -1065,10 +1112,10 @@ fn test_status_transition_logic() {"Complete should not be checked");assert!(- should_check(&StudioRecordingStatus::Failed {+ !should_check(&StudioRecordingStatus::Failed {error: "Some error".to_string()}),- "Failed with other error should be checked"+ "Failed with other error should not be checked");assert!(!should_check(&StudioRecordingStatus::Failed {