Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop): tolerate unavailable log directories at startup

Richie McIlroy3c918489cb9e
diff --git a/apps/desktop/src-tauri/src/crash_sentinel.rs b/apps/desktop/src-tauri/src/crash_sentinel.rs
index f394c8f9b..8a49480bc 100644
--- a/apps/desktop/src-tauri/src/crash_sentinel.rs
+++ b/apps/desktop/src-tauri/src/crash_sentinel.rs
@@ -78,8 +78,20 @@ pub struct UnexpectedTermination {
/// report that unexpected termination to Sentry. Call once at startup, after Sentry
/// is initialised. Returns details of the previous session's unexpected termination,
/// or `None` if the previous session shut down cleanly.
-pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination> {
- let path = logs_dir.join(SENTINEL_FILE);
+pub fn init(logs_dir: Option<&Path>, app_version: &str) -> Option<UnexpectedTermination> {
+ let os = format!(
+ "{} {}",
+ tauri_plugin_os::platform(),
+ tauri_plugin_os::version()
+ );
+ let arch = tauri_plugin_os::arch().to_string();
+ sentry::configure_scope(|scope| {
+ scope.set_tag("os.full", &os);
+ scope.set_tag("arch", &arch);
+ scope.set_tag("app.version", app_version);
+ });
+
+ let path = logs_dir?.join(SENTINEL_FILE);
let mut previous_termination = None;
if let Ok(contents) = std::fs::read_to_string(&path) {
@@ -104,13 +116,6 @@ pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination>
let _ = std::fs::remove_file(&path);
}
- let os = format!(
- "{} {}",
- tauri_plugin_os::platform(),
- tauri_plugin_os::version()
- );
- let arch = tauri_plugin_os::arch().to_string();
-
let record = SessionRecord {
pid: std::process::id(),
started_at: chrono::Utc::now().to_rfc3339(),
@@ -126,12 +131,6 @@ pub fn init(logs_dir: &Path, app_version: &str) -> Option<UnexpectedTermination>
write_record(&path, &record);
- sentry::configure_scope(|scope| {
- scope.set_tag("os.full", &os);
- scope.set_tag("arch", &arch);
- scope.set_tag("app.version", app_version);
- });
-
*SESSION.lock().unwrap() = Some(ActiveSession {
path,
record,
@@ -344,3 +343,35 @@ fn write_record(path: &Path, record: &SessionRecord) {
Err(error) => tracing::warn!(%error, "Failed to serialize crash sentinel"),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sentinel_is_disabled_without_a_directory_and_works_when_available() {
+ assert!(init(None, "test").is_none());
+ assert!(SESSION.lock().unwrap().is_none());
+ enter_gpu_init_phase();
+ exit_gpu_init_phase();
+ enter_blur_session();
+ exit_blur_session();
+ mark_clean_exit();
+ assert!(SESSION.lock().unwrap().is_none());
+
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join(SENTINEL_FILE);
+ assert!(init(Some(directory.path()), "test").is_none());
+ let read_record = || {
+ serde_json::from_str::<SessionRecord>(&std::fs::read_to_string(&path).unwrap()).unwrap()
+ };
+ assert_eq!(read_record().app_version, "test");
+ enter_gpu_init_phase();
+ assert!(read_record().gpu_init_phase);
+ exit_gpu_init_phase();
+ assert!(!read_record().gpu_init_phase);
+ mark_clean_exit();
+ assert!(!path.exists());
+ assert!(SESSION.lock().unwrap().is_none());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index a78c37064..2fa168636 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1490,7 +1490,7 @@ pub struct App {
camera_cleanup_done: bool,
camera_feed: ActorRef<feeds::camera::CameraFeed>,
server_url: String,
- logs_dir: PathBuf,
+ logs_dir: Option<PathBuf>,
disconnected_inputs: HashSet<RecordingInputKind>,
was_camera_only_recording: bool,
}
@@ -6994,11 +6994,11 @@ fn specta_builder() -> tauri_specta::Builder {
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
-pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
+pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: Option<PathBuf>) {
let startup = startup::Startup::default();
// Arm the unexpected-termination sentinel before anything else can crash, and
// report any previous session that died without a clean shutdown.
- let previous_termination = crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
+ let previous_termination = crash_sentinel::init(logs_dir.as_deref(), env!("CARGO_PKG_VERSION"));
configure_windows_graphics_recovery(previous_termination);
// Keep the sentinel's blur marker in sync with live BlurProcessor instances
diff --git a/apps/desktop/src-tauri/src/logging.rs b/apps/desktop/src-tauri/src/logging.rs
index 8551885d6..d9f24315f 100644
--- a/apps/desktop/src-tauri/src/logging.rs
+++ b/apps/desktop/src-tauri/src/logging.rs
@@ -180,7 +180,10 @@ pub(crate) async fn upload_log_file_inner(
.logs_dir
.clone();
let log_bundle = tokio::task::spawn_blocking(move || {
- cap_utils::log_upload::collect(&logs_dir, "cap-desktop.log")
+ logs_dir.as_deref().map_or_else(
+ cap_utils::log_upload::LogBundle::unavailable,
+ |directory| cap_utils::log_upload::collect(directory, "cap-desktop.log"),
+ )
})
.await
.map_err(|_| "Log collection could not finish".to_string())?;
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 16b442384..0cc3adcd2 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -89,22 +89,18 @@ fn main() {
let logs_dir = {
#[cfg(target_os = "macos")]
- let path = dirs::home_dir()
- .unwrap()
- .join("Library/Logs")
- .join("so.cap.desktop");
+ let base_directory = dirs::home_dir();
#[cfg(not(target_os = "macos"))]
- let path = dirs::data_local_dir()
- .unwrap()
- .join("so.cap.desktop")
- .join("logs");
+ let base_directory = dirs::data_local_dir();
+
+ let path = resolve_log_directory(base_directory);
#[cfg(debug_assertions)]
let path =
match cap_desktop_lib::initialize_stop_editor_benchmark(create_benchmark_log_directory)
{
- Ok(directory) => directory.unwrap_or(path),
+ Ok(directory) => directory.or(path),
Err(error) => {
eprintln!("Invalid Stop benchmark invocation: {error}");
std::process::exit(2);
@@ -114,40 +110,46 @@ fn main() {
path
};
- let (info_file_writer, _info_logger_guard) =
- match create_log_appender(&logs_dir, "cap-desktop.log") {
- Some(appender) => {
- let (writer, guard) = tracing_appender::non_blocking(
- cap_utils::diagnostic_writer::DiagnosticWriter::new(
- appender,
- &logs_dir,
- "cap-desktop.log",
- ),
- );
- let queue_errors = writer.error_counter();
- cap_utils::operation_diagnostics::install_queue_loss_counter(move || {
- queue_errors.dropped_lines()
- });
- let diagnostic_writer = writer.clone();
- cap_utils::operation_diagnostics::install_sink(
- cap_utils::operation_diagnostics::AppInfo {
- flavor: "tauri",
- version: env!("CARGO_PKG_VERSION"),
- source_revision: option_env!("CAP_BUILD_REVISION"),
- debug_build: cfg!(debug_assertions),
- source_dirty: option_env!("CAP_BUILD_DIRTY").map(|value| value == "true"),
- },
- move |bytes| {
- use std::io::Write;
- let _ = diagnostic_writer.clone().write_all(bytes);
- },
- );
- (Some(writer), Some(guard))
- }
- None => (None, None),
- };
+ if logs_dir.is_none() {
+ eprintln!("Log directory is unavailable; file logging and persistent crash detection are disabled; console logging remains enabled");
+ }
- let errors_file_appender = create_log_appender(&logs_dir, "cap-desktop-errors.log");
+ let (info_file_writer, _info_logger_guard) = match (
+ logs_dir.as_deref(),
+ create_log_appender(logs_dir.as_deref(), "cap-desktop.log"),
+ ) {
+ (Some(logs_dir), Some(appender)) => {
+ let (writer, guard) = tracing_appender::non_blocking(
+ cap_utils::diagnostic_writer::DiagnosticWriter::new(
+ appender,
+ logs_dir,
+ "cap-desktop.log",
+ ),
+ );
+ let queue_errors = writer.error_counter();
+ cap_utils::operation_diagnostics::install_queue_loss_counter(move || {
+ queue_errors.dropped_lines()
+ });
+ let diagnostic_writer = writer.clone();
+ cap_utils::operation_diagnostics::install_sink(
+ cap_utils::operation_diagnostics::AppInfo {
+ flavor: "tauri",
+ version: env!("CARGO_PKG_VERSION"),
+ source_revision: option_env!("CAP_BUILD_REVISION"),
+ debug_build: cfg!(debug_assertions),
+ source_dirty: option_env!("CAP_BUILD_DIRTY").map(|value| value == "true"),
+ },
+ move |bytes| {
+ use std::io::Write;
+ let _ = diagnostic_writer.clone().write_all(bytes);
+ },
+ );
+ (Some(writer), Some(guard))
+ }
+ _ => (None, None),
+ };
+
+ let errors_file_appender = create_log_appender(logs_dir.as_deref(), "cap-desktop-errors.log");
let (otel_layer, _tracer) = if cfg!(debug_assertions) {
use opentelemetry::trace::TracerProvider;
@@ -234,12 +236,23 @@ fn main() {
});
}
+fn resolve_log_directory(base_directory: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
+ base_directory.map(|directory| {
+ #[cfg(target_os = "macos")]
+ let directory = directory.join("Library/Logs").join("so.cap.desktop");
+ #[cfg(not(target_os = "macos"))]
+ let directory = directory.join("so.cap.desktop").join("logs");
+ directory
+ })
+}
+
fn create_log_appender(
- directory: &std::path::Path,
+ directory: Option<&std::path::Path>,
prefix: &str,
) -> Option<tracing_appender::rolling::RollingFileAppender> {
use std::io::Write;
+ let directory = directory?;
match tracing_appender::rolling::RollingFileAppender::builder()
.rotation(tracing_appender::rolling::Rotation::DAILY)
.filename_prefix(prefix)
@@ -317,9 +330,9 @@ fn create_benchmark_log_directory(
Ok(directory.to_path_buf())
}
-fn install_panic_hook(logs_dir: std::path::PathBuf) {
+fn install_panic_hook(logs_dir: Option<std::path::PathBuf>) {
let prev = std::panic::take_hook();
- let panics_log = logs_dir.join("panics.log");
+ let panics_log = logs_dir.map(|directory| directory.join("panics.log"));
std::panic::set_hook(Box::new(move |info| {
let location = info
.location()
@@ -338,7 +351,7 @@ fn install_panic_hook(logs_dir: std::path::PathBuf) {
let pid = std::process::id();
write_panic_record(
- &panics_log,
+ panics_log.as_deref(),
&timestamp,
pid,
&thread_name,
@@ -363,7 +376,7 @@ fn install_panic_hook(logs_dir: std::path::PathBuf) {
}
fn write_panic_record(
- path: &std::path::Path,
+ path: Option<&std::path::Path>,
timestamp: &str,
pid: u32,
thread_name: &str,
@@ -372,6 +385,9 @@ fn write_panic_record(
backtrace: &std::backtrace::Backtrace,
) {
use std::io::Write;
+ let Some(path) = path else {
+ return;
+ };
let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
@@ -388,7 +404,7 @@ fn write_panic_record(
#[cfg(test)]
mod logging_tests {
- use super::create_log_appender;
+ use super::{create_log_appender, resolve_log_directory, write_panic_record};
use std::{io::Write, path::PathBuf};
struct LogDirectory(PathBuf);
@@ -414,12 +430,59 @@ mod logging_tests {
}
}
+ #[test]
+ fn missing_base_directory_disables_file_logging_without_a_fallback() {
+ let directory = resolve_log_directory(None);
+ assert!(directory.is_none());
+ assert!(create_log_appender(directory.as_deref(), "cap-desktop.log").is_none());
+ assert!(create_log_appender(directory.as_deref(), "cap-desktop-errors.log").is_none());
+ write_panic_record(
+ None,
+ "timestamp",
+ 1,
+ "test",
+ "test:1",
+ "synthetic panic",
+ &std::backtrace::Backtrace::disabled(),
+ );
+ }
+
+ #[test]
+ fn available_base_directory_preserves_the_platform_log_path() {
+ let base = LogDirectory::new();
+ #[cfg(target_os = "macos")]
+ let expected = base.0.join("Library/Logs/so.cap.desktop");
+ #[cfg(not(target_os = "macos"))]
+ let expected = base.0.join("so.cap.desktop/logs");
+ assert_eq!(resolve_log_directory(Some(base.0.clone())), Some(expected));
+ assert!(std::fs::read_dir(&base.0).unwrap().next().is_none());
+ }
+
+ #[test]
+ fn available_panic_log_preserves_existing_records() {
+ let directory = LogDirectory::new();
+ let path = directory.0.join("panics.log");
+ std::fs::write(&path, "existing record\n").unwrap();
+ write_panic_record(
+ Some(&path),
+ "timestamp",
+ 1,
+ "test",
+ "test:1",
+ "synthetic panic",
+ &std::backtrace::Backtrace::disabled(),
+ );
+ let records = std::fs::read_to_string(path).unwrap();
+ assert!(records.starts_with("existing record\n"));
+ assert!(records.contains("synthetic panic"));
+ }
+
#[test]
fn healthy_log_destination_preserves_existing_records() {
let directory = LogDirectory::new();
let destination = directory.0.join("nested");
for record in ["first\n", "second\n"] {
- let mut appender = create_log_appender(&destination, "cap.log").unwrap();
+ let mut appender = create_log_appender(Some(&destination), "cap.log").unwrap();
appender.write_all(record.as_bytes()).unwrap();
appender.flush().unwrap();
}
@@ -436,7 +499,7 @@ mod logging_tests {
let directory = LogDirectory::new();
let destination = directory.0.join("blocked");
std::fs::write(&destination, "existing file").unwrap();
- assert!(create_log_appender(&destination, "cap.log").is_none());
+ assert!(create_log_appender(Some(&destination), "cap.log").is_none());
assert_eq!(
std::fs::read_to_string(destination).unwrap(),
"existing file"
@@ -451,8 +514,8 @@ mod logging_tests {
let date = today + chrono::Duration::days(days);
std::fs::create_dir(directory.0.join(format!("cap.log.{date}"))).unwrap();
}
- assert!(create_log_appender(&directory.0, "cap.log").is_none());
- assert!(create_log_appender(&directory.0, "other.log").is_some());
+ assert!(create_log_appender(Some(&directory.0), "cap.log").is_none());
+ assert!(create_log_appender(Some(&directory.0), "other.log").is_some());
}
}
diff --git a/crates/utils/src/log_upload.rs b/crates/utils/src/log_upload.rs
index 2e23ffc5c..a206e092e 100644
--- a/crates/utils/src/log_upload.rs
+++ b/crates/utils/src/log_upload.rs
@@ -24,6 +24,19 @@ pub struct LogBundle {
pub directory_available: bool,
}
+impl LogBundle {
+ pub fn unavailable() -> Self {
+ let text = "Log directory is unavailable.\n".to_string();
+ Self {
+ ordinary_end: text.len(),
+ text,
+ files: Vec::new(),
+ directory_entries_scanned: 0,
+ directory_available: false,
+ }
+ }
+}
+
pub struct PreparedUpload {
pub log: String,
pub context: String,
@@ -164,8 +177,7 @@ pub fn collect(dir: &Path, prefix: &str) -> LogBundle {
directory_available: false,
};
let Ok(entries) = std::fs::read_dir(dir) else {
- bundle.text.push_str("Log directory is unavailable.\n");
- return bundle;
+ return LogBundle::unavailable();
};
bundle.directory_available = true;
let mut candidates = Vec::new();
@@ -250,6 +262,28 @@ mod tests {
use super::*;
use std::io::Write;
+ #[test]
+ fn unavailable_directory_produces_an_explicit_support_bundle() {
+ let bundle = LogBundle::unavailable();
+ assert!(!bundle.directory_available);
+ assert_eq!(bundle.directory_entries_scanned, 0);
+ assert!(bundle.files.is_empty());
+ let upload = prepare_upload(
+ bundle,
+ serde_json::json!({}),
+ Some("{}"),
+ Some("synthetic report"),
+ str::to_string,
+ );
+ assert_eq!(upload.log, "Log directory is unavailable.\n");
+ assert_eq!(upload.diagnostics.as_deref(), Some("{}"));
+ assert_eq!(upload.report.as_deref(), Some("synthetic report"));
+ let context: serde_json::Value = serde_json::from_str(&upload.context).unwrap();
+ assert_eq!(context["logCoverage"]["directoryAvailable"], false);
+ assert_eq!(context["logCoverage"]["directoryEntriesScanned"], 0);
+ assert_eq!(context["logCoverage"]["files"], serde_json::json!([]));
+ }
+
#[test]
fn retained_history_fits_with_large_metadata_and_recent_events() {
let dir = tempfile::tempdir().unwrap();