//! Bounded accepted-observation feed, independent of browser connections. use crate::{ history::History, lifecycle::Signal, realtime::{ObservationBatch, TargetStore}, services::Services, }; use axum::{ Router, extract::State, http::{HeaderMap, StatusCode}, response::{IntoResponse, Response}, routing::get, }; use std::sync::{ Arc, Mutex, atomic::{AtomicU64, Ordering}, }; #[derive(Clone, Default)] struct Health { dropped: Arc, error: Arc>>, } async fn status(State(health): State, headers: HeaderMap) -> Response { if !crate::maps::local_request(&headers) { return StatusCode::FORBIDDEN.into_response(); } let error = health.error.lock().ok().and_then(|e| *e); let mut response=axum::Json(serde_json::json!({"droppedObservations":health.dropped.load(Ordering::Relaxed),"error":error})).into_response(); response .headers_mut() .insert("cache-control", "no-store".parse().unwrap()); response } pub fn start( services: Services, history: History, live: TargetStore, stop: Signal, ) -> crate::error::Result<(Router, tokio::task::JoinHandle>)> { let health = Health::default(); let state = health.clone(); // Each item is a bounded receiver batch. Producers reserve capacity before // updating live state, so an accepted observation cannot be lost here. let (tx, mut rx) = tokio::sync::mpsc::channel(32); live.install_feed(tx)?; let task = tokio::spawn(async move { let mut engine = None; struct Pending { observations: ObservationBatch, active: Vec, now: u64, alerts_done: bool, } let mut pending: Option = None; let mut interval = tokio::time::interval(std::time::Duration::from_millis(250)); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { if pending.is_none() { let first = tokio::select! { _ = stop.cancelled() => None, batch = rx.recv() => batch, _ = interval.tick() => None, }; // Coalesce bursts without making single-line receivers wait // for the full monitoring interval on every small batch. if first.is_some() { tokio::select! { _ = stop.cancelled() => {}, _ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {}, } } let now = crate::realtime::now_ms(); let Ok(store) = live.lock() else { return Err("实时存储不可用".into()); }; let mut observations = first.unwrap_or_default(); while let Ok(batch) = rx.try_recv() { observations.extend(batch); } pending = Some(Pending { observations, active: store.frame(None, now).targets, now, alerts_done: false, }); } else { tokio::select! { _ = stop.cancelled() => {}, _ = interval.tick() => {} } } let Some(batch) = pending.as_ref() else { continue; }; if !batch.alerts_done { match services .monitor( engine.clone(), &batch.observations, &batch.active, batch.now, ) .await { Ok(next) => { engine = Some(next); if let Some(batch) = pending.as_mut() { batch.alerts_done = true; } } Err(error) => { if stop.is_cancelled() { return Err(error); } if let Ok(mut status) = state.error.lock() { *status = Some("告警保存失败,正在重试;请检查数据库和磁盘"); } continue; } } } let Some(batch) = pending.as_ref() else { continue; }; match history.record(&batch.observations).await { Ok(()) => { pending = None; if let Ok(mut status) = state.error.lock() { *status = None; } } Err(error) => { if stop.is_cancelled() { return Err(error); } if let Ok(mut status) = state.error.lock() { *status = Some("历史轨迹保存失败,正在重试;请检查数据库和磁盘"); } } } if stop.is_cancelled() && pending.is_none() && rx.is_empty() { history.flush().await?; break; } } Ok(()) }); Ok(( Router::new() .route("/api/monitoring/status", get(status)) .with_state(health), task, )) } #[cfg(test)] mod tests { use super::*; use axum::{body::Body, http::Request}; use rid_shared::{ Observation, target_lists::{ListKind, Mutation}, }; use std::time::Duration; use tower::ServiceExt; #[tokio::test] async fn history_retry_does_not_duplicate_committed_alerts() { let dir = tempfile::tempdir().unwrap(); let config = crate::config::SqliteConfig::default(); let services = Services::open(dir.path().into(), &config).await.unwrap(); services .save_list( "TEST", Mutation { list_kind: ListKind::Black, note: String::new(), expected_revision: 0, }, ) .await .unwrap(); let history = History::open(dir.path(), &config).await.unwrap(); let history_db = rusqlite::Connection::open(dir.path().join("registry/data/track-history.sqlite")) .unwrap(); history_db.execute_batch("CREATE TRIGGER fail_track BEFORE INSERT ON track_points BEGIN SELECT RAISE(ABORT,'test'); END;").unwrap(); let live = crate::realtime::new_store(); let stop = Signal::new(); let (status, task) = start( services.clone(), history.clone(), live.clone(), stop.clone(), ) .unwrap(); let now = crate::realtime::now_ms(); let observation = Observation { target_id: "TEST".into(), receiver_id: "RX".into(), source_epoch: 1, sequence: 1, longitude: Some(118.7), latitude: Some(32.0), altitude_m: None, heading_deg: None, telemetry: None, }; live.apply_batch(vec![observation], now).await.unwrap(); tokio::time::timeout(Duration::from_secs(3), async { loop { let response = status .clone() .oneshot( Request::builder() .uri("/api/monitoring/status") .body(Body::empty()) .unwrap(), ) .await .unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 8192) .await .unwrap(); let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); if value["error"] .as_str() .is_some_and(|s| s.contains("历史轨迹")) { break; } tokio::time::sleep(Duration::from_millis(20)).await; } }) .await .unwrap(); tokio::task::spawn_blocking(move || history_db.execute_batch("DROP TRIGGER fail_track")) .await .unwrap() .unwrap(); let history_router = crate::history::router(history.clone()); tokio::time::timeout(Duration::from_secs(3), async { loop { let response = history_router .clone() .oneshot( Request::builder() .uri(format!( "/api/history/points?targetId=TEST&fromMs=0&toMs={}", now + 1000 )) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 8192) .await .unwrap(); let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); if value["entries"] .as_array() .is_some_and(|entries| entries.len() == 1) { break; } tokio::time::sleep(Duration::from_millis(20)).await; } }) .await .unwrap(); let events = services .events(&std::collections::HashMap::new()) .await .unwrap(); assert_eq!(events["entries"].as_array().unwrap().len(), 1); stop.cancel(); task.await.unwrap().unwrap(); history.close().await; services.close().await; } #[tokio::test] async fn small_receiver_frames_are_drained_without_waiting_a_tick_per_batch() { let dir = tempfile::tempdir().unwrap(); let config = crate::config::SqliteConfig::default(); let services = Services::open(dir.path().into(), &config).await.unwrap(); let history = History::open(dir.path(), &config).await.unwrap(); let live = crate::realtime::new_store(); let stop = Signal::new(); let (_, task) = start( services.clone(), history.clone(), live.clone(), stop.clone(), ) .unwrap(); let now = crate::realtime::now_ms(); tokio::time::timeout(Duration::from_secs(3), async { for sequence in 1..=512 { let observation = Observation { target_id: "TEST".into(), receiver_id: "RX".into(), source_epoch: 1, sequence, longitude: None, latitude: None, altitude_m: None, heading_deg: None, telemetry: None, }; assert_eq!(live.apply_batch(vec![observation], now).await.unwrap().0, 1); } }) .await .expect("small frames stalled behind the monitoring interval"); stop.cancel(); task.await.unwrap().unwrap(); assert_eq!(live.lock().unwrap().metrics().accepted, 512); history.close().await; services.close().await; } #[tokio::test] async fn graceful_shutdown_flushes_the_last_sampled_position() { let dir = tempfile::tempdir().unwrap(); let config = crate::config::SqliteConfig::default(); let services = Services::open(dir.path().into(), &config).await.unwrap(); let history = History::open(dir.path(), &config).await.unwrap(); let live = crate::realtime::new_store(); let stop = Signal::new(); let (_, task) = start( services.clone(), history.clone(), live.clone(), stop.clone(), ) .unwrap(); let now = crate::realtime::now_ms(); let mut observation = Observation { target_id: "TEST".into(), receiver_id: "RX".into(), source_epoch: 1, sequence: 1, longitude: Some(118.0), latitude: Some(32.0), altitude_m: None, heading_deg: None, telemetry: None, }; live.apply_batch(vec![observation.clone()], now) .await .unwrap(); observation.sequence = 2; observation.longitude = Some(118.1); live.apply_batch(vec![observation], now + 500) .await .unwrap(); stop.cancel(); tokio::time::timeout(Duration::from_secs(3), task) .await .unwrap() .unwrap() .unwrap(); let response = crate::history::router(history.clone()) .oneshot( Request::builder() .uri(format!( "/api/history/points?targetId=TEST&fromMs={}&toMs={}", now - 1, now + 1000 )) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let bytes = axum::body::to_bytes(response.into_body(), 8192) .await .unwrap(); let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let points = value["entries"].as_array().unwrap(); assert_eq!(points.len(), 2); assert_eq!(points[1]["longitude"], 118.1); history.close().await; services.close().await; } }