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

chore: add unit tests for /health and fix benchmarks

Louis Beaumontd06e68a2ef21
diff --git a/Cargo.toml b/Cargo.toml
index 2bde69407..3a6aee33c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,11 +4,11 @@ members = [
"screenpipe-vision",
"screenpipe-audio",
"screenpipe-server",
- # "examples/apps/screenpipe-app-tauri/src-tauri",
- # "examples/apps/screenpipe-app-dioxus",
+
]
exclude = [
-
+ "examples/apps/screenpipe-app-tauri/src-tauri",
+ "examples/apps/screenpipe-app-dioxus",
]
resolver = "2"
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rs
index 3a92c0183..db38f78ef 100644
--- a/screenpipe-server/benches/db_benchmarks.rs
+++ b/screenpipe-server/benches/db_benchmarks.rs
@@ -16,7 +16,15 @@ async fn setup_large_db(size: usize) -> DatabaseManager {
let text_json = format!(r#"{{"text": "{}"}}"#, ocr_text);
let new_text_json_vs_previous_frame = format!(r#"{{"text": "{}"}}"#, ocr_text);
let raw_data_output_from_ocr = format!(r#"{{"output": "{}"}}"#, ocr_text);
- db.insert_ocr_text(frame_id, &ocr_text, &text_json, &new_text_json_vs_previous_frame, &raw_data_output_from_ocr).await.unwrap();
+ db.insert_ocr_text(
+ frame_id,
+ &ocr_text,
+ &text_json,
+ &new_text_json_vs_previous_frame,
+ &raw_data_output_from_ocr,
+ )
+ .await
+ .unwrap();
let audio_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();
let audio_text = format!("Audio transcription {}", rng.gen::<u32>());
@@ -47,7 +55,9 @@ fn bench_search(c: &mut Criterion) {
|b| {
b.to_async(&rt).iter(|| async {
let db = setup_large_db(size).await;
- db.search(query, content_type, 100, 0).await.unwrap()
+ db.search(query, content_type, 100, 0, None, None)
+ .await
+ .unwrap()
});
},
);
@@ -59,4 +69,4 @@ fn bench_search(c: &mut Criterion) {
}
criterion_group!(benches, bench_search);
-criterion_main!(benches);
\ No newline at end of file
+criterion_main!(benches);
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 95128e457..47d3b6797 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -46,7 +46,7 @@ pub struct AudioResult {
}
pub struct DatabaseManager {
- pool: SqlitePool,
+ pub pool: SqlitePool,
}
impl DatabaseManager {
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 30fb15325..eea825144 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -1,14 +1,17 @@
pub mod core;
mod db;
+pub mod logs;
mod plugin;
mod resource_monitor;
mod server;
mod video;
-pub mod logs;
pub use core::{start_continuous_recording, RecorderControl};
pub use db::{ContentType, DatabaseManager, SearchResult};
+pub use logs::MultiWriter;
pub use resource_monitor::ResourceMonitor;
+pub use server::health_check;
+pub use server::AppState;
+pub use server::HealthCheckResponse;
pub use server::Server;
pub use video::VideoCapture;
-pub use logs::MultiWriter;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index ea830136f..e059c779b 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -32,12 +32,12 @@ use tower_http::{
use crate::plugin::ApiPluginLayer;
-pub(crate) struct AppState {
- db: Arc<DatabaseManager>,
- vision_control: Arc<AtomicBool>,
- audio_devices_control_sender: Sender<(AudioDevice, DeviceControl)>,
- devices_status: HashMap<AudioDevice, DeviceControl>,
- app_start_time: DateTime<Utc>,
+pub struct AppState {
+ pub db: Arc<DatabaseManager>,
+ pub vision_control: Arc<AtomicBool>,
+ pub audio_devices_control_sender: Sender<(AudioDevice, DeviceControl)>,
+ pub devices_status: HashMap<AudioDevice, DeviceControl>,
+ pub app_start_time: DateTime<Utc>,
}
#[derive(Deserialize)]
@@ -143,15 +143,15 @@ fn default_limit() -> u32 {
20
}
-#[derive(Serialize)]
-pub(crate) struct HealthCheckResponse {
- status: String,
- last_frame_timestamp: Option<DateTime<Utc>>,
- last_audio_timestamp: Option<DateTime<Utc>>,
- frame_status: String,
- audio_status: String,
- message: String,
- verbose_instructions: Option<String>,
+#[derive(Serialize, Deserialize)]
+pub struct HealthCheckResponse {
+ pub status: String,
+ pub last_frame_timestamp: Option<DateTime<Utc>>,
+ pub last_audio_timestamp: Option<DateTime<Utc>>,
+ pub frame_status: String,
+ pub audio_status: String,
+ pub message: String,
+ pub verbose_instructions: Option<String>,
}
pub(crate) async fn search(
@@ -355,14 +355,15 @@ pub(crate) async fn get_devices(
JsonResponse(devices)
}
-pub(crate) async fn health_check(
- State(state): State<Arc<AppState>>,
-) -> JsonResponse<HealthCheckResponse> {
- let (last_frame, last_audio) = state
- .db
- .get_latest_timestamps()
- .await
- .unwrap_or((None, None));
+pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<HealthCheckResponse> {
+ let (last_frame, last_audio) = match state.db.get_latest_timestamps().await {
+ Ok((frame, audio)) => (frame, audio),
+ Err(e) => {
+ error!("Failed to get latest timestamps: {}", e);
+ (None, None)
+ }
+ };
+
let now = Utc::now();
let threshold = Duration::from_secs(60);
let loading_threshold = Duration::from_secs(120);
@@ -415,7 +416,7 @@ pub(crate) async fn health_check(
} else {
(
"Unhealthy",
- "Some systems are not functioning properly.".to_string(),
+ format!("Some systems are not functioning properly. Frame status: {}, Audio status: {}", frame_status, audio_status),
Some("If you're experiencing issues, please try the following steps:\n\
1. Restart the application.\n\
2. If using a desktop app, reset your Screenpipe OS permissions.\n\
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
new file mode 100644
index 000000000..c12fb1c58
--- /dev/null
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -0,0 +1,193 @@
+#[cfg(test)]
+mod tests {
+ use axum::body::Body;
+ use axum::http::{Request, StatusCode};
+ use axum::Router;
+ use axum::{body::to_bytes, routing::get};
+ use chrono::{Duration, Utc};
+ use screenpipe_server::HealthCheckResponse;
+ use screenpipe_server::{health_check, AppState, DatabaseManager}; // Adjust this import based on your actual module structure
+ use std::collections::HashMap;
+ use std::sync::atomic::AtomicBool;
+ use std::sync::Arc;
+ use tower::ServiceExt; // for `oneshot` and `ready`
+
+ async fn setup_test_app() -> (Router, Arc<AppState>) {
+ let db = Arc::new(DatabaseManager::new("sqlite::memory:").await.unwrap());
+ let app_state = Arc::new(AppState {
+ db: db.clone(),
+ vision_control: Arc::new(AtomicBool::new(false)),
+ audio_devices_control_sender: tokio::sync::mpsc::channel(100).0,
+ devices_status: HashMap::new(),
+ app_start_time: Utc::now(),
+ });
+
+ let app = Router::new()
+ .route("/health", get(health_check))
+ .with_state(app_state.clone());
+
+ (app, app_state)
+ }
+
+ #[tokio::test]
+ async fn test_health_endpoint_initial_state() {
+ let (app, _) = setup_test_app().await;
+
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri("/health")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let health_response: HealthCheckResponse = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(health_response.status, "Loading");
+ assert!(health_response.last_frame_timestamp.is_none());
+ assert!(health_response.last_audio_timestamp.is_none());
+ assert_eq!(health_response.frame_status, "Loading");
+ assert_eq!(health_response.audio_status, "Loading");
+ assert!(!health_response.message.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_health_endpoint_after_initialization() {
+ let (app, _state) = setup_test_app().await;
+
+ // Simulate passage of time
+ tokio::time::sleep(tokio::time::Duration::from_secs(121)).await;
+
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri("/health")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let health_response: HealthCheckResponse = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(health_response.status, "Unhealthy");
+ assert!(health_response.last_frame_timestamp.is_none());
+ assert!(health_response.last_audio_timestamp.is_none());
+ assert_eq!(health_response.frame_status, "No data");
+ assert_eq!(health_response.audio_status, "No data");
+ assert!(!health_response.message.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_health_endpoint_with_recent_data() {
+ let (app, state) = setup_test_app().await;
+ let db = &state.db;
+
+ // Simulate passage of time
+ tokio::time::sleep(tokio::time::Duration::from_secs(120)).await;
+
+
+ // Insert some recent data
+ let _ = db.insert_video_chunk("test_video.mp4").await.unwrap();
+ let frame_id = db.insert_frame().await.unwrap();
+ let _ = db
+ .insert_ocr_text(frame_id, "Test OCR", "{}", "{}", "{}")
+ .await
+ .unwrap();
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.wav").await.unwrap();
+ let _ = db
+ .insert_audio_transcription(audio_chunk_id, "Test Audio", 0)
+ .await
+ .unwrap();
+
+ // Simulate passage of time
+ tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
+
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri("/health")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let health_response: HealthCheckResponse = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(health_response.status, "Healthy");
+ assert!(health_response.last_frame_timestamp.is_some());
+ assert!(health_response.last_audio_timestamp.is_some());
+ assert_eq!(health_response.frame_status, "OK");
+ assert_eq!(health_response.audio_status, "OK");
+ assert!(!health_response.message.is_empty());
+ }
+
+ #[tokio::test]
+ async fn test_health_endpoint_with_stale_data() {
+ let (app, state) = setup_test_app().await;
+ let db = &state.db;
+
+ // Insert some stale data (more than 60 seconds old)
+ let stale_time = Utc::now() - Duration::seconds(61);
+ let _ = db.insert_video_chunk("test_video.mp4").await.unwrap();
+ let frame_id = db.insert_frame().await.unwrap();
+ let _ = db
+ .insert_ocr_text(frame_id, "Test OCR", "{}", "{}", "{}")
+ .await
+ .unwrap();
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.wav").await.unwrap();
+ let _ = db
+ .insert_audio_transcription(audio_chunk_id, "Test Audio", 0)
+ .await
+ .unwrap();
+
+ // Manually update timestamps to make them stale
+ sqlx::query("UPDATE frames SET timestamp = ?")
+ .bind(stale_time)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+ sqlx::query("UPDATE audio_transcriptions SET timestamp = ?")
+ .bind(stale_time)
+ .execute(&db.pool)
+ .await
+ .unwrap();
+
+ // Simulate passage of time
+ tokio::time::sleep(tokio::time::Duration::from_secs(121)).await;
+
+ let response = app
+ .oneshot(
+ Request::builder()
+ .uri("/health")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let health_response: HealthCheckResponse = serde_json::from_slice(&body).unwrap();
+
+ assert_eq!(health_response.status, "Unhealthy");
+ assert!(health_response.last_frame_timestamp.is_some());
+ assert!(health_response.last_audio_timestamp.is_some());
+ assert_eq!(health_response.frame_status, "Stale");
+ assert_eq!(health_response.audio_status, "Stale");
+ assert!(!health_response.message.is_empty());
+ }
+}
diff --git a/screenpipe-vision/benches/vision_benchmark.rs b/screenpipe-vision/benches/vision_benchmark.rs
index b3c2e65fa..8e9a4dbae 100644
--- a/screenpipe-vision/benches/vision_benchmark.rs
+++ b/screenpipe-vision/benches/vision_benchmark.rs
@@ -13,7 +13,7 @@ async fn benchmark_continuous_capture(duration_secs: u64) -> f64 {
let (result_tx, mut result_rx) = mpsc::channel(100);
let capture_handle = tokio::spawn(async move {
- continuous_capture(&mut control_rx, result_tx, Duration::from_millis(100)).await;
+ continuous_capture(&mut control_rx, result_tx, Duration::from_millis(100), false).await;
});
// Run for specified duration