Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): settle export estimates after rendering panics
Richie McIlroy2b8842b33332
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dd28b8a80..1b24b780a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -326,6 +326,16 @@ jobs:env:LD_LIBRARY_PATH: ${{ format('{0}/target/native-deps/lib:{0}/target/debug:{0}/target/{1}/debug', github.workspace, matrix.settings.target) }}+ - name: Test export estimate request lifecycle+ shell: bash+ run: |+ if [[ "$RUNNER_OS" == "Windows" ]]; then+ export PATH="$(cygpath "$GITHUB_WORKSPACE/target/debug"):$PATH"+ elif [[ "$RUNNER_OS" == "Linux" ]]; then+ export LD_LIBRARY_PATH="$GITHUB_WORKSPACE/target/native-deps/lib:$GITHUB_WORKSPACE/target/debug:$GITHUB_WORKSPACE/target/${{ matrix.settings.target }}/debug${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+ fi+ cargo test --locked -p cap-desktop --test export_estimate_request+- name: Build GPUI desktopshell: bashrun: ./scripts/build-gpui-binary.sh debug ${{ matrix.settings.target }}diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex f5b87f89c..956352b31 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -1,3 +1,5 @@+mod estimate_request;+use crate::editor_window::{OptionalWindowEditorInstance, WindowEditorInstance};use crate::{FramesRendered, get_video_metadata};use cap_export::{ExporterBase, make_cursor_only_project};@@ -1728,17 +1730,13 @@ pub struct ExportEstimates {pub estimated_size_mb: f64,}-static EXPORT_ESTIMATE_CANCELLATIONS: LazyLock<Mutex<HashMap<PathBuf, Arc<AtomicBool>>>> =- LazyLock::new(Mutex::default);+static EXPORT_ESTIMATE_REQUESTS: LazyLock<estimate_request::EstimateRequests> =+ LazyLock::new(estimate_request::EstimateRequests::default);#[tauri::command]#[specta::specta]pub fn cancel_export_estimates(editor: WindowEditorInstance) {- if let Ok(cancellations) = EXPORT_ESTIMATE_CANCELLATIONS.lock()- && let Some(cancel) = cancellations.get(&editor.project_path)- {- cancel.store(true, Ordering::Release);- }+ EXPORT_ESTIMATE_REQUESTS.cancel(&editor.project_path);}#[tauri::command]@@ -1753,41 +1751,34 @@ pub async fn get_export_estimates(if path != editor.project_path {return Err("Export estimate does not match the open project".into());}- let cancel = Arc::new(AtomicBool::new(false));- if let Some(previous) = EXPORT_ESTIMATE_CANCELLATIONS- .lock()- .map_err(|error| error.to_string())?- .insert(path.clone(), cancel.clone())- {- previous.store(true, Ordering::Release);- }- let result = async {- let project = load_export_preview_config(path.clone(), settings.cursor_only()).await?;- let settings = match settings {- ExportSettings::Mp4(settings) => cap_export::settings::ExportSettings::Mp4(settings),- ExportSettings::Gif(settings) => cap_export::settings::ExportSettings::Gif(settings),- ExportSettings::Mov(settings) => cap_export::settings::ExportSettings::Mov(settings),- };- cap_export::estimates::estimate_export(- (**editor).clone(),- project,- settings,- cancel.clone(),- move |estimate| {- let _ = on_estimate.send(estimate);- },- )+ let request = EXPORT_ESTIMATE_REQUESTS.start(path.clone())?;+ let cancel = request.cancellation();+ request+ .run(async {+ let project = load_export_preview_config(path, settings.cursor_only()).await?;+ let settings = match settings {+ ExportSettings::Mp4(settings) => {+ cap_export::settings::ExportSettings::Mp4(settings)+ }+ ExportSettings::Gif(settings) => {+ cap_export::settings::ExportSettings::Gif(settings)+ }+ ExportSettings::Mov(settings) => {+ cap_export::settings::ExportSettings::Mov(settings)+ }+ };+ cap_export::estimates::estimate_export(+ (**editor).clone(),+ project,+ settings,+ cancel,+ move |estimate| {+ let _ = on_estimate.send(estimate);+ },+ )+ .await+ }).await- }- .await;- if let Ok(mut cancellations) = EXPORT_ESTIMATE_CANCELLATIONS.lock()- && cancellations- .get(&path)- .is_some_and(|current| Arc::ptr_eq(current, &cancel))- {- let _ = cancellations.remove(&path);- }- result}fn export_estimates_for_duration(diff --git a/apps/desktop/src-tauri/src/export/estimate_request.rs b/apps/desktop/src-tauri/src/export/estimate_request.rsnew file mode 100644index 000000000..f653d777b--- /dev/null+++ b/apps/desktop/src-tauri/src/export/estimate_request.rs@@ -0,0 +1,235 @@+use futures::FutureExt;+use std::{+ collections::HashMap,+ future::Future,+ panic::AssertUnwindSafe,+ path::{Path, PathBuf},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+};++#[derive(Default)]+pub struct EstimateRequests {+ cancellations: Mutex<HashMap<PathBuf, Arc<AtomicBool>>>,+}++impl EstimateRequests {+ pub fn start(&self, path: PathBuf) -> Result<EstimateRequest<'_>, String> {+ let cancel = Arc::new(AtomicBool::new(false));+ if let Some(previous) = self+ .cancellations+ .lock()+ .map_err(|error| error.to_string())?+ .insert(path.clone(), cancel.clone())+ {+ previous.store(true, Ordering::Release);+ }+ Ok(EstimateRequest {+ requests: self,+ path,+ cancel,+ })+ }++ pub fn cancel(&self, path: &Path) {+ if let Ok(cancellations) = self.cancellations.lock()+ && let Some(cancel) = cancellations.get(path)+ {+ cancel.store(true, Ordering::Release);+ }+ }+}++pub struct EstimateRequest<'a> {+ requests: &'a EstimateRequests,+ path: PathBuf,+ cancel: Arc<AtomicBool>,+}++impl EstimateRequest<'_> {+ pub fn cancellation(&self) -> Arc<AtomicBool> {+ self.cancel.clone()+ }++ pub async fn run<T>(+ self,+ future: impl Future<Output = Result<T, String>>,+ ) -> Result<T, String> {+ match AssertUnwindSafe(future).catch_unwind().await {+ Ok(result) => result,+ Err(_) => {+ tracing::error!(target: "cap_desktop_export", "Export estimate panicked");+ Err("Export estimate failed unexpectedly".to_string())+ }+ }+ }+}++impl Drop for EstimateRequest<'_> {+ fn drop(&mut self) {+ self.cancel.store(true, Ordering::Release);+ if let Ok(mut cancellations) = self.requests.cancellations.lock()+ && cancellations+ .get(&self.path)+ .is_some_and(|current| Arc::ptr_eq(current, &self.cancel))+ {+ let _ = cancellations.remove(&self.path);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use futures::{executor::block_on, future};+ use std::task::Poll;++ struct DropSignal(Arc<AtomicBool>);++ impl Drop for DropSignal {+ fn drop(&mut self) {+ self.0.store(true, Ordering::Release);+ }+ }++ #[test]+ fn successful_request_returns_estimate_and_cleans_up() {+ let requests = EstimateRequests::default();+ let request = requests.start("example.cap".into()).unwrap();+ let cancel = request.cancellation();+ let result = block_on(request.run(async { Ok(42) }));+ assert_eq!(result, Ok(42));+ assert!(cancel.load(Ordering::Acquire));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn ordinary_error_is_preserved_and_cleans_up() {+ let requests = EstimateRequests::default();+ let request = requests.start("example.cap".into()).unwrap();+ let result = block_on(request.run(async { Err::<(), _>("Invalid resolution".into()) }));+ assert_eq!(result, Err("Invalid resolution".into()));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn polling_panic_returns_safe_error_and_drops_sample_resources() {+ let requests = EstimateRequests::default();+ let request = requests.start("example.cap".into()).unwrap();+ let cancel = request.cancellation();+ let dropped = Arc::new(AtomicBool::new(false));+ let signal = dropped.clone();+ let result = block_on(request.run(async move {+ let _sample = DropSignal(signal);+ let mut yielded = false;+ future::poll_fn(|cx| {+ if yielded {+ Poll::Ready(())+ } else {+ yielded = true;+ cx.waker().wake_by_ref();+ Poll::Pending+ }+ })+ .await;+ future::poll_fn(|_| -> Poll<Result<(), String>> {+ panic!("synthetic pipeline validation failure with private details")+ })+ .await+ }));+ assert_eq!(result, Err("Export estimate failed unexpectedly".into()));+ assert!(dropped.load(Ordering::Acquire));+ assert!(cancel.load(Ordering::Acquire));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn dropping_pending_request_cancels_and_cleans_up() {+ let requests = EstimateRequests::default();+ let request = requests.start("example.cap".into()).unwrap();+ let cancel = request.cancellation();+ let mut running = Box::pin(request.run(future::pending::<Result<(), String>>()));+ assert!(running.as_mut().now_or_never().is_none());+ assert!(!cancel.load(Ordering::Acquire));+ drop(running);+ assert!(cancel.load(Ordering::Acquire));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn superseded_request_cannot_remove_replacement() {+ let requests = EstimateRequests::default();+ let path = PathBuf::from("example.cap");+ let first = requests.start(path.clone()).unwrap();+ let first_cancel = first.cancellation();+ let second = requests.start(path.clone()).unwrap();+ let second_cancel = second.cancellation();+ assert!(first_cancel.load(Ordering::Acquire));+ assert_eq!(block_on(first.run(async { Ok(()) })), Ok(()));+ assert!(!second_cancel.load(Ordering::Acquire));+ assert!(Arc::ptr_eq(+ requests.cancellations.lock().unwrap().get(&path).unwrap(),+ &second_cancel,+ ));+ requests.cancel(&path);+ assert!(second_cancel.load(Ordering::Acquire));+ drop(second);+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn panicking_request_cannot_remove_replacement() {+ let requests = EstimateRequests::default();+ let path = PathBuf::from("example.cap");+ let first = requests.start(path.clone()).unwrap();+ let second = requests.start(path.clone()).unwrap();+ let second_cancel = second.cancellation();+ let result = block_on(first.run(future::poll_fn(|_| -> Poll<Result<(), String>> {+ panic!("synthetic failure")+ })));+ assert!(result.is_err());+ assert!(Arc::ptr_eq(+ requests.cancellations.lock().unwrap().get(&path).unwrap(),+ &second_cancel,+ ));+ assert!(!second_cancel.load(Ordering::Acquire));+ requests.cancel(&path);+ assert!(second_cancel.load(Ordering::Acquire));+ }++ #[test]+ fn dropping_unpolled_request_cleans_up_registration() {+ let requests = EstimateRequests::default();+ let request = requests.start("example.cap".into()).unwrap();+ let cancel = request.cancellation();+ drop(request.run(future::pending::<Result<(), String>>()));+ assert!(cancel.load(Ordering::Acquire));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }++ #[test]+ fn cancellation_is_scoped_to_the_requested_project() {+ let requests = EstimateRequests::default();+ let first = requests.start("first.cap".into()).unwrap();+ let second = requests.start("second.cap".into()).unwrap();+ requests.cancel(Path::new("first.cap"));+ assert!(first.cancellation().load(Ordering::Acquire));+ assert!(!second.cancellation().load(Ordering::Acquire));+ }++ #[test]+ fn new_request_can_succeed_after_a_panic() {+ let requests = EstimateRequests::default();+ let first = requests.start("example.cap".into()).unwrap();+ let result = block_on(first.run(future::poll_fn(|_| -> Poll<Result<(), String>> {+ panic!("synthetic failure")+ })));+ assert!(result.is_err());+ let second = requests.start("example.cap".into()).unwrap();+ assert!(!second.cancellation().load(Ordering::Acquire));+ assert_eq!(block_on(second.run(async { Ok(42) })), Ok(42));+ assert!(requests.cancellations.lock().unwrap().is_empty());+ }+}diff --git a/apps/desktop/src-tauri/tests/export_estimate_request.rs b/apps/desktop/src-tauri/tests/export_estimate_request.rsnew file mode 100644index 000000000..9516cd6bd--- /dev/null+++ b/apps/desktop/src-tauri/tests/export_estimate_request.rs@@ -0,0 +1,2 @@+#[path = "../src/export/estimate_request.rs"]+mod estimate_request;