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: websocket for health (#1310)

tribhuwan4d6bc95487ee
diff --git a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
index a7e6eaae3..e16085983 100644
--- a/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
+++ b/screenpipe-app-tauri/lib/hooks/use-health-check.tsx
@@ -1,5 +1,4 @@
import { useState, useEffect, useCallback, useRef } from "react";
-
import { debounce } from "lodash";
import posthog from "posthog-js";
@@ -61,41 +60,35 @@ function shouldSendPosthogEvent(eventName: string): boolean {
export function useHealthCheck() {
const [health, setHealth] = useState<HealthCheckResponse | null>(null);
const [isServerDown, setIsServerDown] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
- const abortControllerRef = useRef<AbortController | null>(null);
+ const [isLoading, setIsLoading] = useState(true);
const healthRef = useRef(health);
+ const wsRef = useRef<WebSocket | null>(null);
const previousHealthStatus = useRef<string | null>(null);
const unhealthyTransitionsRef = useRef<number>(0);
+ const retryIntervalRef = useRef<NodeJS.Timeout | null>(null);
const fetchHealth = useCallback(async () => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
+ if (wsRef.current) {
+ wsRef.current.close();
}
- abortControllerRef.current = new AbortController();
-
- try {
- setIsLoading(true);
- const response = await fetch("http://localhost:3030/health", {
- cache: "no-store",
- signal: abortControllerRef.current.signal,
- headers: {
- "Cache-Control": "no-cache",
- Pragma: "no-cache",
- },
- });
+ const ws = new WebSocket("ws://127.0.0.1:3030/ws/health");
+ wsRef.current = ws;
- if (!response.ok) {
- if (shouldSendPosthogEvent("health_check_http_error")) {
- posthog.capture("health_check_http_error", {
- status: response.status,
- statusText: response.statusText,
- });
- }
- throw new Error(`HTTP error! status: ${response.status}`);
+ ws.onopen = () => {
+ setIsLoading(false);
+ if (retryIntervalRef.current) {
+ clearInterval(retryIntervalRef.current);
+ retryIntervalRef.current = null;
}
+ };
- const data: HealthCheckResponse = await response.json();
+ ws.onmessage = (event) => {
+ const data: HealthCheckResponse = JSON.parse(event.data);
+ if (isHealthChanged(healthRef.current, data)) {
+ setHealth(data);
+ healthRef.current = data;
+ }
if (
data.status === "unhealthy" &&
@@ -117,55 +110,80 @@ export function useHealthCheck() {
previousHealthStatus.current = data.status;
- if (isHealthChanged(healthRef.current, data)) {
- setHealth(data);
- healthRef.current = data;
- }
-
- setIsServerDown(false);
- } catch (error) {
- if (error instanceof Error && error.name === "AbortError") {
- return;
- }
-
- if (!isServerDown && shouldSendPosthogEvent("health_check_server_down")) {
- posthog.capture("health_check_server_down", {
- error: error instanceof Error ? error.message : "Unknown error",
+ if (data.status === "unhealthy") {
+ posthog.capture("health_check_unhealthy", {
+ frame_status: data.frame_status,
+ audio_status: data.audio_status,
+ ui_status: data.ui_status,
+ message: data.message,
});
}
+ };
- if (!isServerDown) {
- const errorHealth: HealthCheckResponse = {
- last_frame_timestamp: null,
- last_audio_timestamp: null,
- last_ui_timestamp: null,
- frame_status: "error",
- audio_status: "error",
- ui_status: "error",
- status: "error",
- status_code: 500,
- message: "Failed to fetch health status. Server might be down.",
- };
- setHealth(errorHealth);
- healthRef.current = errorHealth;
- }
- } finally {
+ ws.onerror = (event) => {
+ const error = event as ErrorEvent;
+ const errorHealth: HealthCheckResponse = {
+ status: "error",
+ status_code: 500,
+ last_frame_timestamp: null,
+ last_audio_timestamp: null,
+ last_ui_timestamp: null,
+ frame_status: "error",
+ audio_status: "error",
+ ui_status: "error",
+ message: error.message,
+ };
+ setHealth(errorHealth);
+ posthog.capture("health_check_error", {
+ error: error.message,
+ });
+ setIsServerDown(true);
setIsLoading(false);
- }
- }, [isServerDown, setIsLoading]);
+ if (!retryIntervalRef.current) {
+ retryIntervalRef.current = setInterval(fetchHealth, 2000);
+ }
+ };
- const debouncedFetchHealth = useCallback(debounce(fetchHealth, 1000), [
- fetchHealth,
- ]);
+ ws.onclose = () => {
+ const errorHealth: HealthCheckResponse = {
+ status: "error",
+ status_code: 500,
+ last_frame_timestamp: null,
+ last_audio_timestamp: null,
+ last_ui_timestamp: null,
+ frame_status: "error",
+ audio_status: "error",
+ ui_status: "error",
+ message: "WebSocket connection closed",
+ };
+ setHealth(errorHealth);
+ setIsServerDown(true);
+ if (!retryIntervalRef.current) {
+ retryIntervalRef.current = setInterval(fetchHealth, 2000)
+ }
+ };
+ }, []);
+
+ const debouncedFetchHealth = useCallback(() => {
+ return new Promise<void>((resolve) => {
+ debounce(() => {
+ if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
+ fetchHealth().then(resolve);
+ } else {
+ resolve();
+ }
+ }, 1000)();
+ });
+ }, [fetchHealth]);
useEffect(() => {
fetchHealth();
- const interval = setInterval(fetchHealth, 1000);
-
return () => {
- clearInterval(interval);
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
+ if (wsRef.current) {
+ wsRef.current.close();
+ }
+ if (retryIntervalRef.current) {
+ clearInterval(retryIntervalRef.current);
}
};
}, [fetchHealth]);
@@ -178,3 +196,4 @@ export function useHealthCheck() {
debouncedFetchHealth,
} as HealthCheckHook;
}
+
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index de8b42f72..eed8b720b 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1,7 +1,7 @@
use axum::{
body::Body,
extract::{
- ws::{Message, WebSocket, WebSocketUpgrade},
+ ws::{Message, WebSocket, WebSocketUpgrade, CloseFrame},
Json, Path, Query, State,
},
http::StatusCode,
@@ -261,6 +261,7 @@ fn default_limit() -> u32 {
#[derive(Serialize, Deserialize)]
pub struct HealthCheckResponse {
pub status: String,
+ pub status_code: u16,
pub last_frame_timestamp: Option<DateTime<Utc>>,
pub last_audio_timestamp: Option<DateTime<Utc>>,
pub last_ui_timestamp: Option<DateTime<Utc>>,
@@ -604,7 +605,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
}
};
- let (overall_status, message, verbose_instructions) = if (frame_status == "ok"
+ let (overall_status, message, verbose_instructions, status_code) = if (frame_status == "ok"
|| frame_status == "disabled")
&& (audio_status == "ok" || audio_status == "disabled")
&& (ui_status == "ok" || ui_status == "disabled")
@@ -613,6 +614,7 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
"healthy",
"all systems are functioning normally.".to_string(),
None,
+ 200,
)
} else {
let mut unhealthy_systems = Vec::new();
@@ -630,12 +632,14 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
"unhealthy",
format!("some systems are not functioning properly: {}. frame status: {}, audio status: {}, ui status: {}",
unhealthy_systems.join(", "), frame_status, audio_status, ui_status),
- Some("if you're experiencing issues, please try contacting us on discord".to_string())
+ Some("if you're experiencing issues, please try contacting us on discord".to_string()),
+ 500,
)
};
JsonResponse(HealthCheckResponse {
status: overall_status.to_string(),
+ status_code,
last_frame_timestamp: last_frame,
last_audio_timestamp: audio,
last_ui_timestamp: last_ui,
@@ -646,7 +650,6 @@ pub async fn health_check(State(state): State<Arc<AppState>>) -> JsonResponse<He
verbose_instructions,
})
}
-
// Request and response structs
#[derive(Deserialize)]
struct DownloadPipeRequest {
@@ -1930,6 +1933,34 @@ async fn handle_socket(socket: WebSocket, query: Query<EventsQuery>) {
debug!("WebSocket connection closed");
}
+async fn ws_health_handler(ws: WebSocketUpgrade, State(state): State<Arc<AppState>>) -> Response {
+ ws.on_upgrade(move |socket| handle_health_socket(socket, state))
+}
+
+async fn handle_health_socket(mut socket: WebSocket, state: Arc<AppState>) {
+ let mut interval = tokio::time::interval(Duration::from_secs(5));
+
+ loop {
+ tokio::select! {
+ _ = interval.tick() => {
+ let health_response = health_check(State(state.clone())).await;
+ let health_status = serde_json::to_string(&health_response.0).unwrap_or_default();
+ if let Err(e) = socket.send(Message::Text(health_status)).await {
+ error!("Failed to send health status: {}", e);
+ break;
+ }
+ }
+ result = socket.recv() => {
+ if result.is_none() {
+ break;
+ }
+ }
+ }
+ }
+
+ debug!("WebSocket connection closed gracefully");
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
let cors = CorsLayer::new()
.allow_origin(Any)
@@ -1960,6 +1991,7 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/pipes/update", post(update_pipe_config_handler))
.route("/pipes/delete", post(delete_pipe_handler))
.route("/health", get(health_check))
+ .route("/ws/health", get(ws_health_handler))
.route("/raw_sql", post(execute_raw_sql))
.route("/add", post(add_to_database))
.route("/stream/frames", get(stream_frames_handler))