Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: resource monitoring & small hack to avoid crashes

Louis Beaumontb32569b6320d
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 76e489802..285e74b9e 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -62,6 +62,9 @@ env_logger = "0.10"
# Cli ! shouldn't be required if using as lib
clap = { version = "4.3", features = ["derive"] }
+# Memory watchdog
+sysinfo = "0.29.0"
+
[dev-dependencies]
tempfile = "3.3.0"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index 789e9896f..bbad284fd 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -2,13 +2,13 @@ use std::{
fs,
net::SocketAddr,
sync::{mpsc::channel, Arc},
+ time::Duration,
};
use clap::Parser;
-use log::info;
-use tokio::time::Duration;
+use log::{info, LevelFilter};
-use screenpipe_server::{start_continuous_recording, DatabaseManager, Server};
+use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
@@ -28,45 +28,58 @@ struct Cli {
/// Disable audio recording
#[arg(long, default_value_t = false)]
disable_audio: bool,
+
+ /// Memory usage threshold for restart (in percentage)
+ #[arg(long, default_value_t = 80.0)]
+ memory_threshold: f64,
+
+ /// Runtime threshold for restart (in minutes)
+ #[arg(long, default_value_t = 60)]
+ runtime_threshold: u64,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Initialize logging
- use env_logger::Builder;
- use log::LevelFilter;
let cli = Cli::parse();
- Builder::new()
+ ResourceMonitor::new(cli.memory_threshold, cli.runtime_threshold)
+ .start_monitoring(Duration::from_secs(10)); // Log every 10 seconds
+
+ env_logger::Builder::new()
.filter(None, LevelFilter::Info)
.filter_module("tokenizers", LevelFilter::Error)
.filter_module("rusty_tesseract", LevelFilter::Error)
.init();
- let local_data_dir = ensure_local_data_dir()?;
+ let local_data_dir = Arc::new(ensure_local_data_dir()?);
+ let local_data_dir_record = local_data_dir.clone();
let db = Arc::new(
DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir))
.await
.unwrap(),
);
+ let db_record = db.clone();
let db_server = db.clone();
+
// Channel for controlling the recorder
let (_control_tx, control_rx) = channel();
// Start continuous recording in a separate task
- let local_data_dir_clone = local_data_dir.clone();
- let _recording_task = tokio::spawn(async move {
- let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
-
- start_continuous_recording(
- db,
- &local_data_dir_clone,
- cli.fps,
- audio_chunk_duration,
- control_rx,
- !cli.disable_audio,
- )
- .await
+ let _recording_task = tokio::spawn({
+ async move {
+ let audio_chunk_duration = Duration::from_secs(cli.audio_chunk_duration);
+
+ start_continuous_recording(
+ db_record,
+ local_data_dir_record,
+ cli.fps,
+ audio_chunk_duration,
+ control_rx,
+ !cli.disable_audio,
+ )
+ .await
+ }
});
tokio::spawn(async move {
@@ -80,15 +93,7 @@ async fn main() -> anyhow::Result<()> {
// Keep the main thread running
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
- // You can add logic here to send control messages if needed
- // For example:
- // control_tx.send(RecorderControl::Pause).await?;
- // control_tx.send(RecorderControl::Resume).await?;
}
-
- // This part will never be reached in the current implementation
- // control_tx.send(RecorderControl::Stop).await?;
- // recording_task.await??;
}
fn ensure_local_data_dir() -> anyhow::Result<String> {
diff --git a/screenpipe-server/src/bin/screenpipe-video.rs b/screenpipe-server/src/bin/screenpipe-video.rs
index 59cfa6a0c..1f27689b6 100644
--- a/screenpipe-server/src/bin/screenpipe-video.rs
+++ b/screenpipe-server/src/bin/screenpipe-video.rs
@@ -30,7 +30,7 @@ fn main() {
let fps = 10.0;
let new_chunk_callback = {
- move |file_path: String| {
+ move |file_path: &str| {
info!("New chunk: {}", file_path);
}
};
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 0542b9e10..6ed05b879 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -2,13 +2,15 @@ use crate::{DatabaseManager, VideoCapture};
use anyhow::Result;
use chrono::Utc;
use log::{debug, error, info};
-use screenpipe_audio::{continuous_audio_capture, save_audio_to_file, ControlMessage};
+use screenpipe_audio::{
+ continuous_audio_capture, save_audio_to_file, ControlMessage as AudioControlMessage,
+};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver};
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tokio::runtime::Runtime;
-
pub enum RecorderControl {
Pause,
Resume,
@@ -17,7 +19,7 @@ pub enum RecorderControl {
pub async fn start_continuous_recording(
db: Arc<DatabaseManager>,
- output_path: &str,
+ output_path: Arc<String>,
fps: f64,
audio_chunk_duration: Duration,
control_rx: Receiver<RecorderControl>,
@@ -31,159 +33,138 @@ pub async fn start_continuous_recording(
let db_manager_video = Arc::clone(&db);
let db_manager_audio = Arc::clone(&db);
- let new_chunk_callback = move |file_path: String| {
- let db_manager = Arc::clone(&db);
+ let is_running = Arc::new(AtomicBool::new(true));
+ let is_running_video = Arc::clone(&is_running);
+ let is_running_audio = Arc::clone(&is_running);
+
+ let output_path_video = Arc::clone(&output_path);
+ let output_path_audio = Arc::clone(&output_path);
+
+ let video_handle = tokio::spawn(async move {
+ record_video(db_manager_video, output_path_video, fps, is_running_video).await
+ });
+
+ let audio_handle = if enable_audio {
+ let handle = tokio::spawn(async move {
+ record_audio(
+ db_manager_audio,
+ output_path_audio,
+ audio_chunk_duration,
+ is_running_audio,
+ )
+ .await
+ });
+ Some(handle)
+ } else {
+ None
+ };
+
+ // Control loop
+ tokio::spawn(async move {
+ while let Ok(ctrl) = control_rx.recv() {
+ match ctrl {
+ RecorderControl::Stop => {
+ is_running.store(false, Ordering::SeqCst);
+ break;
+ }
+ _ => {} // Handle Pause and Resume if needed
+ }
+ }
+ });
+
+ video_handle.await??;
+ if let Some(handle) = audio_handle {
+ handle.await??;
+ }
+
+ info!("Continuous recording stopped");
+ Ok(())
+}
+
+async fn record_video(
+ db: Arc<DatabaseManager>,
+ output_path: Arc<String>,
+ fps: f64,
+ is_running: Arc<AtomicBool>,
+) -> Result<()> {
+ let db_chunk_callback = Arc::clone(&db);
+ let new_chunk_callback = move |file_path: &str| {
let rt = Runtime::new().expect("Failed to create runtime");
- if let Err(e) = rt.block_on(db_manager.insert_video_chunk(&file_path)) {
+ if let Err(e) = rt.block_on(db_chunk_callback.insert_video_chunk(file_path)) {
error!("Failed to insert new video chunk: {}", e);
}
};
- let video_capture = VideoCapture::new(output_path, fps, new_chunk_callback);
- let control_rx = Arc::new(Mutex::new(control_rx));
- let control_rx_video = Arc::clone(&control_rx);
- let control_rx_audio = Arc::clone(&control_rx);
-
- let video_thread = thread::spawn(move || {
- let runtime = tokio::runtime::Runtime::new().unwrap();
- let _ = runtime.block_on(async {
- info!("Starting video capture thread");
- let mut is_paused = false;
- loop {
- match control_rx_video.lock().unwrap().try_recv() {
- Ok(RecorderControl::Pause) => {
- info!("Pausing video capture");
- is_paused = true;
- }
- Ok(RecorderControl::Resume) => {
- info!("Resuming video capture");
- is_paused = false;
- }
- Ok(RecorderControl::Stop) => {
- info!("Stopping video capture");
- break;
- }
- Err(_) => {}
- }
- if !is_paused {
- if let Some(frame) = video_capture.get_latest_frame() {
- match db_manager_video.insert_frame().await {
- Ok(frame_id) => {
- if let Err(e) = db_manager_video
- .insert_ocr_text(frame_id, &frame.text)
- .await
- {
- error!("Failed to insert OCR text: {}", e);
- return Err(e.into());
- }
- debug!("Inserted frame {} with OCR text", frame_id);
- }
- Err(e) => {
- error!("Failed to insert frame: {}", e);
- return Err(e.into());
- }
- }
+ let video_capture = VideoCapture::new(&output_path, fps, new_chunk_callback);
+
+ while is_running.load(Ordering::SeqCst) {
+ if let Some(frame) = video_capture.get_latest_frame() {
+ match db.insert_frame().await {
+ Ok(frame_id) => {
+ if let Err(e) = db.insert_ocr_text(frame_id, &frame.text).await {
+ error!("Failed to insert OCR text: {}", e);
}
+ debug!("Inserted frame {} with OCR text", frame_id);
+ }
+ Err(e) => {
+ error!("Failed to insert frame: {}", e);
}
- tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;
}
- Ok::<_, anyhow::Error>(())
- });
- });
+ }
+ tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;
+ }
- if enable_audio {
- let (audio_control_tx, audio_control_rx) = mpsc::channel();
- let (audio_result_tx, audio_result_rx) = mpsc::channel();
+ video_capture.stop();
+ Ok(())
+}
- let audio_thread = thread::spawn(move || {
- info!("Starting audio capture thread");
- continuous_audio_capture(audio_control_rx, audio_result_tx, audio_chunk_duration)
- });
+async fn record_audio(
+ db: Arc<DatabaseManager>,
+ output_path: Arc<String>,
+ chunk_duration: Duration,
+ is_running: Arc<AtomicBool>,
+) -> Result<()> {
+ let (audio_control_tx, audio_control_rx) = mpsc::channel();
+ let (audio_result_tx, audio_result_rx) = mpsc::channel();
- let output_path_clone = output_path.to_string();
-
- let audio_processing_thread = thread::spawn(move || {
- let runtime = tokio::runtime::Runtime::new().unwrap();
- let _ = runtime.block_on(async {
- info!("Starting audio processing thread");
- let mut is_paused = false;
- loop {
- match control_rx_audio.lock().unwrap().try_recv() {
- Ok(RecorderControl::Pause) => {
- info!("Pausing audio processing");
- is_paused = true;
- }
- Ok(RecorderControl::Resume) => {
- info!("Resuming audio processing");
- is_paused = false;
- }
- Ok(RecorderControl::Stop) => {
- info!("Stopping audio processing");
- break;
- }
- Err(_) => {}
- }
+ let audio_thread = thread::spawn(move || {
+ info!("Starting audio capture thread");
+ continuous_audio_capture(audio_control_rx, audio_result_tx, chunk_duration)
+ });
- if !is_paused {
- match audio_result_rx.recv() {
- Ok(result) => {
- info!("Received audio chunk, processing...");
- info!("Audio chunk size: {}", result.audio.len());
- let time = Utc::now();
- let file_path = format!("{}/{}.wav", output_path_clone, time);
- info!("Saving audio chunk to {}", file_path);
- match save_audio_to_file(&result.audio, &file_path) {
- Ok(_) => info!("Successfully saved audio file"),
- Err(e) => error!("Failed to save audio file: {}", e),
- }
-
- match db_manager_audio.insert_audio_chunk(&file_path).await {
- Ok(audio_chunk_id) => {
- debug!("Inserted audio chunk with id: {}", audio_chunk_id);
- if let Err(e) = db_manager_audio
- .insert_audio_transcription(
- audio_chunk_id,
- &result.text,
- 0,
- )
- .await
- // TODO offset
- {
- error!("Failed to insert audio transcription: {}", e);
- } else {
- debug!(
- "Inserted audio transcription for chunk {}",
- audio_chunk_id
- );
- }
- }
- Err(e) => error!("Failed to insert audio chunk: {}", e),
- }
- }
- Err(e) => {
- error!("Failed to receive audio chunk: {}", e);
- // should terminate the thread
- break;
- }
+ while is_running.load(Ordering::SeqCst) {
+ match audio_result_rx.recv_timeout(Duration::from_secs(1)) {
+ Ok(result) => {
+ let time = Utc::now();
+ let file_path = format!("{}/{}.wav", output_path, time);
+ if let Err(e) = save_audio_to_file(&result.audio, &file_path) {
+ error!("Failed to save audio file: {}", e);
+ continue;
+ }
+
+ match db.insert_audio_chunk(&file_path).await {
+ Ok(audio_chunk_id) => {
+ if let Err(e) = db
+ .insert_audio_transcription(audio_chunk_id, &result.text, 0)
+ .await
+ {
+ error!("Failed to insert audio transcription: {}", e);
+ } else {
+ debug!("Inserted audio transcription for chunk {}", audio_chunk_id);
}
}
+ Err(e) => error!("Failed to insert audio chunk: {}", e),
}
- Ok::<_, anyhow::Error>(())
- });
- });
-
- // Wait for threads to finish
- info!("Waiting for threads to finish");
- video_thread.join().unwrap();
- audio_processing_thread.join().unwrap();
- audio_control_tx.send(ControlMessage::Stop).unwrap();
- let _ = audio_thread.join().unwrap();
- } else {
- // Only wait for video thread if audio is disabled
- info!("Waiting for video thread to finish");
- video_thread.join().unwrap();
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => continue,
+ Err(e) => {
+ error!("Failed to receive audio chunk: {}", e);
+ break;
+ }
+ }
}
- info!("Continuous recording stopped");
+ audio_control_tx.send(AudioControlMessage::Stop).unwrap();
+ let _ = audio_thread.join().expect("Failed to join audio thread");
Ok(())
}
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index af05ecc85..610098a6f 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -2,8 +2,10 @@ mod core;
mod db;
mod server;
mod video;
+mod resource_monitor;
pub use core::{start_continuous_recording, RecorderControl};
pub use db::{ContentType, DatabaseManager, SearchResult};
pub use server::Server;
pub use video::{extract_frames_from_video, VideoCapture};
+pub use resource_monitor::ResourceMonitor;
\ No newline at end of file
diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rs
new file mode 100644
index 000000000..39d24b216
--- /dev/null
+++ b/screenpipe-server/src/resource_monitor.rs
@@ -0,0 +1,100 @@
+use log::{error, info, warn};
+use std::process::Command;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::thread;
+use std::time::{Duration, Instant};
+use sysinfo::{PidExt, ProcessExt, System, SystemExt};
+
+pub struct ResourceMonitor {
+ open_files: AtomicUsize,
+ active_threads: AtomicUsize,
+ start_time: Instant,
+ memory_threshold: f64,
+ runtime_threshold: Duration,
+}
+
+impl ResourceMonitor {
+ pub fn new(memory_threshold: f64, runtime_threshold_minutes: u64) -> Arc<Self> {
+ Arc::new(Self {
+ open_files: AtomicUsize::new(0),
+ active_threads: AtomicUsize::new(0),
+ start_time: Instant::now(),
+ memory_threshold,
+ runtime_threshold: Duration::from_secs(runtime_threshold_minutes * 60),
+ })
+ }
+
+ fn log_status(&self, sys: &System) {
+ let pid = std::process::id();
+ if let Some(process) = sys.process(sysinfo::Pid::from_u32(pid)) {
+ let memory_usage = process.memory() as f64 / 1024.0; // Convert to KB
+ let total_memory = sys.total_memory() as f64 / 1024.0; // Convert to KB
+ let memory_usage_percent = (memory_usage / total_memory) * 100.0;
+ let cpu_usage = process.cpu_usage();
+ let runtime = self.start_time.elapsed();
+
+ info!(
+ "Runtime: {:?}, Memory: {:.2}% ({:.2} KB / {:.2} KB), CPU: {:.2}%, Open files: {}, Active threads: {}",
+ runtime,
+ memory_usage_percent,
+ memory_usage,
+ total_memory,
+ cpu_usage,
+ self.open_files.load(Ordering::SeqCst),
+ self.active_threads.load(Ordering::SeqCst)
+ );
+
+ // Check for restart conditions
+ if memory_usage_percent > self.memory_threshold || runtime > self.runtime_threshold {
+ warn!(
+ "Restarting due to: Memory usage: {:.2}%, Runtime: {:?}",
+ memory_usage_percent, runtime
+ );
+ self.restart();
+ }
+ }
+ }
+
+ fn restart(&self) {
+ warn!("Initiating restart due to resource thresholds...");
+
+ let args: Vec<String> = std::env::args().collect();
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ let mut cmd = Command::new(&args[0]);
+ cmd.args(&args[1..]);
+ let err = cmd.exec();
+ error!("Failed to restart application: {}", err);
+ std::process::exit(1);
+ }
+
+ #[cfg(not(unix))]
+ {
+ // For non-Unix systems, we'll use a less seamless but still functional approach
+ match Command::new(&args[0]).args(&args[1..]).spawn() {
+ Ok(_) => {
+ info!("Application restarted successfully");
+ std::process::exit(0);
+ }
+ Err(e) => {
+ error!("Failed to restart application: {}", e);
+ std::process::exit(1);
+ }
+ }
+ }
+ }
+ pub fn start_monitoring(self: &Arc<Self>, interval: Duration) {
+ let monitor = Arc::clone(self);
+ thread::spawn(move || {
+ let mut sys = System::new_all();
+ loop {
+ sys.refresh_all();
+ monitor.log_status(&sys);
+ thread::sleep(interval);
+ }
+ });
+ }
+}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 412bcd344..18a31a9bc 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -126,7 +126,7 @@ impl VideoCapture {
pub fn new(
output_path: &str,
fps: f64,
- new_chunk_callback: impl Fn(String) + Send + Sync + 'static,
+ new_chunk_callback: impl Fn(&str) + Send + Sync + 'static,
) -> Self {
info!("Starting new video capture");
let (control_tx, control_rx) = channel();
@@ -204,7 +204,7 @@ fn save_frames_as_video(
output_path: &str,
fps: f64,
is_running: Arc<Mutex<bool>>,
- new_chunk_callback: &dyn Fn(String),
+ new_chunk_callback: &dyn Fn(&str),
) {
let frames_per_video = 30; // Adjust this value as needed
let mut frame_count = 0;
@@ -213,7 +213,7 @@ fn save_frames_as_video(
let pool_size = std::cmp::min(pool_size, MAX_THREADS);
let pool = ThreadPool::new(pool_size);
let (sender, receiver): (Sender<Vec<u8>>, Receiver<Vec<u8>>) = channel();
-
+ let sender = Arc::new(sender);
let mut current_ffmpeg: Option<std::process::Child> = None;
let mut current_stdin: Option<std::process::ChildStdin> = None;
@@ -244,7 +244,7 @@ fn save_frames_as_video(
// Start new FFmpeg process with a new output file
let output_file = format!("{}/{}.mp4", output_path, time);
// Call the callback with the new video chunk file path
- new_chunk_callback(output_file.clone()); // TODO better error handling
+ new_chunk_callback(&output_file); // TODO better error handling
let mut child = start_ffmpeg_process(&output_file, fps);
let mut stdin = child.stdin.take().expect("Failed to open stdin");
@@ -271,7 +271,7 @@ fn save_frames_as_video(
}
if let Some(result) = frame_queue.lock().unwrap().pop_front() {
- let sender = sender.clone();
+ let sender = Arc::clone(&sender);
pool.execute(move || {
let mut buffer = Vec::new();
match result