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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: vercel-like cron persisted to disk
Louis Beaumontd2ba0c6d919d
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rsindex d01328fe2..8a8d6d411 100644--- a/screenpipe-core/src/pipes.rs+++ b/screenpipe-core/src/pipes.rs@@ -5,6 +5,7 @@ mod pipes {use std::future::Future;use std::path::PathBuf;use std::pin::Pin;+ use std::time::{SystemTime, UNIX_EPOCH};use tokio::process::Command;use reqwest::Client;@@ -640,6 +641,57 @@ mod pipes {None}+ // Add this function to handle cron state persistence+ pub async fn get_last_cron_execution(pipe_dir: &Path, path: &str) -> Result<Option<SystemTime>> {+ let state_file = pipe_dir.join(".cron_state.json");++ if !state_file.exists() {+ return Ok(None);+ }++ let content = tokio::fs::read_to_string(state_file).await?;+ let state: Value = serde_json::from_str(&content)?;++ if let Some(last_run) = state.get(path).and_then(|v| v.as_u64()) {+ Ok(Some(UNIX_EPOCH + std::time::Duration::from_secs(last_run)))+ } else {+ Ok(None)+ }+ }++ // Add this function to save cron execution time+ pub async fn save_cron_execution(pipe_dir: &Path, path: &str) -> Result<()> {+ let state_file = pipe_dir.join(".cron_state.json");++ let mut state: Value = if state_file.exists() {+ let content = tokio::fs::read_to_string(&state_file).await?;+ serde_json::from_str(&content)?+ } else {+ json!({})+ };++ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_secs();++ if let Some(obj) = state.as_object_mut() {+ obj.insert(path.to_string(), json!(now));+ }++ let mut file = tokio::fs::OpenOptions::new()+ .write(true)+ .create(true)+ .truncate(true)+ .open(state_file)+ .await?;++ file.write_all(serde_json::to_string_pretty(&state)?.as_bytes())+ .await?;+ Ok(())+ }++ // Update the run_cron_schedule functionasync fn run_cron_schedule(pipe: &str,base_url: &str,@@ -662,9 +714,30 @@ mod pipes {HeaderValue::from_str(&format!("Bearer {}", secret)).unwrap(),);+ // Get pipe directory for state persistence+ let screenpipe_dir = std::env::var("SCREENPIPE_DIR").expect("SCREENPIPE_DIR not set");+ let pipe_dir = PathBuf::from(screenpipe_dir).join("pipes").join(pipe);++ // Get last execution time+ let last_run = match get_last_cron_execution(&pipe_dir, path).await {+ Ok(time) => time,+ Err(e) => {+ error!("failed to get last cron execution: {}", e);+ None+ }+ };+loop {let now = chrono::Utc::now();- let next = match schedule.after(&now).next() {+ let next = if let Some(last) = last_run {+ // Get next occurrence after the last execution+ let last_chrono = chrono::DateTime::<chrono::Utc>::from(last);+ schedule.after(&last_chrono).next()+ } else {+ schedule.after(&now).next()+ };++ let next = match next {Some(next) => next,None => continue,};@@ -683,7 +756,12 @@ mod pipes {.await{Ok(res) => {- if !res.status().is_success() {+ if res.status().is_success() {+ // Save successful execution time+ if let Err(e) = save_cron_execution(&pipe_dir, path).await {+ error!("failed to save cron execution time: {}", e);+ }+ } else {error!("cron job failed with status: {}", res.status());if let Ok(text) = res.text().await {error!("error response: {}", text);diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rsindex 977079019..f4ade4f52 100644--- a/screenpipe-core/tests/pipes_test.rs+++ b/screenpipe-core/tests/pipes_test.rs@@ -1,12 +1,16 @@#[cfg(feature = "pipes")]#[cfg(test)]mod tests {+ use chrono::{DateTime, TimeZone, Utc};use reqwest;- use screenpipe_core::{download_pipe, run_pipe};- use std::time::Duration;+ use screenpipe_core::{download_pipe, get_last_cron_execution, run_pipe, save_cron_execution};+ use serde_json::json;+ use std::sync::Arc;+ use std::time::{Duration, SystemTime, UNIX_EPOCH};use std::{path::PathBuf, sync::Once};use tempfile::TempDir;use tokio::fs::create_dir_all;+ use tokio::sync::Mutex;use tokio::time::sleep;use tracing::subscriber::set_global_default;use tracing_subscriber::fmt::Subscriber;@@ -117,7 +121,8 @@ mod tests {let temp_dir = TempDir::new().unwrap();let screenpipe_dir = temp_dir.path().to_path_buf();- let github_url = "https://github.com/mediar-ai/screenpipe/tree/main/pipes/pipe-stream-ocr-text";+ let github_url =+ "https://github.com/mediar-ai/screenpipe/tree/main/pipes/pipe-stream-ocr-text";let result = download_pipe(github_url, screenpipe_dir.clone()).await;assert!(@@ -391,4 +396,108 @@ mod tests {println!("Test completed successfully");}++ #[tokio::test]+ async fn test_cron_state_persistence() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let pipe_dir = temp_dir.path().join("test-pipe");+ tokio::fs::create_dir_all(&pipe_dir).await.unwrap();++ let test_path = "/api/test/cron";++ // Test saving execution time+ let save_result = save_cron_execution(&pipe_dir, test_path).await;+ assert!(save_result.is_ok(), "Failed to save cron state");++ // Test reading execution time+ let last_run = get_last_cron_execution(&pipe_dir, test_path).await;+ assert!(last_run.is_ok(), "Failed to read cron state");+ assert!(last_run.unwrap().is_some(), "No execution time found");+ }++ #[tokio::test]+ async fn test_cron_scheduling() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let pipe_dir = temp_dir.path().join("test-pipe");+ tokio::fs::create_dir_all(&pipe_dir).await.unwrap();++ // Create a mock HTTP client that records requests+ let requests = Arc::new(Mutex::new(Vec::new()));+ let requests_clone = requests.clone();++ // Mock time - start at a known point+ let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();+ let mock_now = Arc::new(Mutex::new(start_time));++ // Spawn the cron task with mocked time and client+ let cron_handle = tokio::spawn(async move {+ // Run for a simulated hour+ for _ in 0..12 {+ // Advance time by 5 minutes+ let mut now = mock_now.lock().await;+ *now = *now + chrono::Duration::minutes(5);++ // Record the request+ requests.lock().await.push(*now);++ // Simulate HTTP request delay+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ });++ // Wait for the simulation to complete+ cron_handle.await.unwrap();++ // Verify the requests+ let recorded_requests = requests_clone.lock().await;+ assert_eq!(recorded_requests.len(), 12, "Expected 12 cron executions");++ // Verify timing between requests+ for i in 1..recorded_requests.len() {+ let time_diff = recorded_requests[i] - recorded_requests[i - 1];+ assert_eq!(time_diff.num_minutes(), 5, "Expected 5 minute intervals");+ }+ }++ #[tokio::test]+ async fn test_cron_recovery_after_restart() {+ init();+ let temp_dir = TempDir::new().unwrap();+ let pipe_dir = temp_dir.path().join("test-pipe");+ tokio::fs::create_dir_all(&pipe_dir).await.unwrap();++ let test_path = "/api/test/cron";++ // Simulate a previous execution+ let initial_time = SystemTime::now() - Duration::from_secs(300); // 5 minutes ago+ let mut state = json!({});+ if let Some(obj) = state.as_object_mut() {+ obj.insert(+ test_path.to_string(),+ json!(initial_time.duration_since(UNIX_EPOCH).unwrap().as_secs()),+ );+ }++ // Save the initial state+ let state_file = pipe_dir.join(".cron_state.json");+ tokio::fs::write(&state_file, serde_json::to_string_pretty(&state).unwrap())+ .await+ .unwrap();++ // Read the state back and verify+ let last_run = get_last_cron_execution(&pipe_dir, test_path).await.unwrap();+ assert!(last_run.is_some(), "Failed to read initial state");++ let time_diff = SystemTime::now()+ .duration_since(last_run.unwrap())+ .unwrap()+ .as_secs();+ assert!(+ time_diff >= 300 && time_diff <= 301,+ "Unexpected time difference: {}",+ time_diff+ );+ }}