1use crate::DistributedRuntime;
5use crate::config::HealthStatus;
6use crate::engine::AsyncEngine;
7use crate::pipeline::SingleIn;
8use crate::protocols::maybe_error::MaybeError;
9use futures::StreamExt;
10use parking_lot::Mutex;
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::time::Duration;
14use tokio::task::JoinHandle;
15use tracing::{debug, error, info, warn};
16
17const CANARY_MAX_WAIT: Duration = Duration::from_secs(600);
21
22pub struct HealthCheckConfig {
24 pub canary_wait_time: Duration,
26 pub request_timeout: Duration,
28}
29
30impl Default for HealthCheckConfig {
31 fn default() -> Self {
32 Self {
33 canary_wait_time: Duration::from_secs(crate::config::DEFAULT_CANARY_WAIT_TIME_SECS),
34 request_timeout: Duration::from_secs(
35 crate::config::DEFAULT_HEALTH_CHECK_REQUEST_TIMEOUT_SECS,
36 ),
37 }
38 }
39}
40
41pub struct HealthCheckManager {
43 drt: DistributedRuntime,
44 config: HealthCheckConfig,
45 endpoint_tasks: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
48}
49
50impl HealthCheckManager {
51 pub fn new(drt: DistributedRuntime, config: HealthCheckConfig) -> Self {
52 Self {
53 drt,
54 config,
55 endpoint_tasks: Arc::new(Mutex::new(HashMap::new())),
56 }
57 }
58
59 pub async fn start(self: Arc<Self>) -> anyhow::Result<()> {
61 let targets = self.drt.system_health().lock().get_health_check_targets();
63
64 info!(
65 "Starting health check tasks for {} endpoints with canary_wait_time: {:?}",
66 targets.len(),
67 self.config.canary_wait_time
68 );
69
70 for (endpoint_subject, _target) in targets {
72 self.spawn_endpoint_health_check_task(endpoint_subject);
73 }
74
75 self.spawn_new_endpoint_monitor().await?;
79
80 info!("HealthCheckManager started successfully with channel-based endpoint discovery");
81 Ok(())
82 }
83
84 fn spawn_endpoint_health_check_task(self: &Arc<Self>, endpoint_subject: String) {
86 let manager = self.clone();
87 let canary_wait = self.config.canary_wait_time;
88 let endpoint_subject_clone = endpoint_subject.clone();
89
90 let notifier = self
92 .drt
93 .system_health()
94 .lock()
95 .get_endpoint_health_check_notifier(&endpoint_subject)
96 .expect("Notifier should exist for registered endpoint");
97 let progress = self
98 .drt
99 .system_health()
100 .lock()
101 .get_endpoint_progress_notifier(&endpoint_subject)
102 .expect("Notifier should exist for registered endpoint");
103
104 let task = tokio::spawn(async move {
105 let endpoint_subject = endpoint_subject_clone;
106 info!("Health check task started for: {}", endpoint_subject);
107
108 let mut canary: Option<JoinHandle<()>> = None;
111
112 loop {
113 tokio::select! {
115 _ = tokio::time::sleep(canary_wait) => {
116 if canary.as_ref().is_some_and(|canary| !canary.is_finished()) {
117 continue;
119 }
120
121 debug!("Canary timer expired for {}, sending health check", endpoint_subject);
123
124 let target = manager.drt.system_health().lock().get_health_check_target(&endpoint_subject);
126
127 if let Some(target) = target {
128 match manager.send_health_check_request(&endpoint_subject, &target.payload, progress.clone()) {
129 Ok(sent) => canary = Some(sent),
130 Err(e) => error!("Failed to send health check for {}: {}", endpoint_subject, e),
131 }
132 } else {
133 error!(
135 "CRITICAL: Health check target for {} disappeared unexpectedly! This indicates a bug. Stopping health check task.",
136 endpoint_subject
137 );
138 break;
139 }
140 }
141
142 _ = notifier.notified() => {
143 debug!("Activity detected for {}, resetting health check timer", endpoint_subject);
148 manager.drt.system_health().lock().set_endpoint_health_status(
149 &endpoint_subject,
150 crate::config::HealthStatus::Ready,
151 );
152 }
153 }
154 }
155
156 info!("Health check task for {} exiting", endpoint_subject);
157 });
158
159 self.endpoint_tasks
161 .lock()
162 .insert(endpoint_subject.clone(), task);
163
164 info!(
165 "Spawned health check task for endpoint: {}",
166 endpoint_subject
167 );
168 }
169
170 async fn spawn_new_endpoint_monitor(self: &Arc<Self>) -> anyhow::Result<()> {
173 let manager = self.clone();
174
175 let mut rx = manager
177 .drt
178 .system_health()
179 .lock()
180 .take_new_endpoint_receiver()
181 .ok_or_else(|| {
182 anyhow::anyhow!("Endpoint receiver already taken - this should only be called once")
183 })?;
184
185 tokio::spawn(async move {
186 info!("Starting dynamic endpoint discovery monitor with channel-based notifications");
187
188 while let Some(endpoint_subject) = rx.recv().await {
189 debug!(
190 "Received endpoint registration via channel: {}",
191 endpoint_subject
192 );
193
194 let already_exists = {
195 let tasks = manager.endpoint_tasks.lock();
196 tasks.contains_key(&endpoint_subject)
197 };
198
199 if already_exists {
200 error!(
201 "CRITICAL: Received registration for endpoint '{}' that already has a health check task!",
202 endpoint_subject
203 );
204 break;
205 }
206
207 info!(
208 "Spawning health check task for new endpoint: {}",
209 endpoint_subject
210 );
211 manager.spawn_endpoint_health_check_task(endpoint_subject);
212 }
213
214 info!("Endpoint discovery monitor exiting - no new endpoints will be monitored!");
215 });
216
217 info!("Dynamic endpoint discovery monitor started");
218 Ok(())
219 }
220
221 fn send_health_check_request(
224 &self,
225 endpoint_subject: &str,
226 payload: &serde_json::Value,
227 progress: Arc<tokio::sync::Notify>,
228 ) -> anyhow::Result<JoinHandle<()>> {
229 debug!(
230 "Sending health check to {} via local registry",
231 endpoint_subject
232 );
233
234 let engine = self
235 .drt
236 .local_endpoint_registry()
237 .get(endpoint_subject)
238 .ok_or_else(|| {
239 anyhow::anyhow!(
240 "Endpoint '{}' not found in local registry, engine may still be initializing",
241 endpoint_subject
242 )
243 })?;
244
245 let system_health = self.drt.system_health().clone();
247 let endpoint_subject_owned = endpoint_subject.to_string();
248 let payload = payload.clone();
249 let timeout = self.config.request_timeout;
250 let max_wait = CANARY_MAX_WAIT.max(timeout);
251
252 let canary = tokio::spawn(async move {
254 let result = timeout_unless_progress(timeout, max_wait, &progress, async {
255 let request = SingleIn::new(payload);
256 match engine.generate(request).await {
257 Ok(mut response_stream) => {
258 let is_healthy = if let Some(response) = response_stream.next().await {
261 if let Some(error) = response.err() {
262 warn!(
263 "Health check error response from {}: {:?}",
264 endpoint_subject_owned, error
265 );
266 false
267 } else {
268 debug!("Health check successful for {}", endpoint_subject_owned);
269 true
270 }
271 } else {
272 warn!(
273 "Health check got no response from {}",
274 endpoint_subject_owned
275 );
276 false
277 };
278
279 tokio::spawn(async move {
280 response_stream.for_each(|_| async {}).await;
282 });
283
284 system_health.lock().set_endpoint_health_status(
286 &endpoint_subject_owned,
287 if is_healthy {
288 HealthStatus::Ready
289 } else {
290 HealthStatus::NotReady
291 },
292 );
293 }
294 Err(e) => {
295 error!(
296 "Health check request failed for {}: {}",
297 endpoint_subject_owned, e
298 );
299 system_health.lock().set_endpoint_health_status(
300 &endpoint_subject_owned,
301 HealthStatus::NotReady,
302 );
303 }
304 }
305 })
306 .await;
307
308 if result.is_none() {
310 warn!("Health check timeout for {}", endpoint_subject_owned);
311 system_health
312 .lock()
313 .set_endpoint_health_status(&endpoint_subject_owned, HealthStatus::NotReady);
314 }
315
316 debug!("Health check completed for {}", endpoint_subject_owned);
317 });
318
319 Ok(canary)
320 }
321}
322
323async fn timeout_unless_progress<T>(
330 timeout: Duration,
331 max_wait: Duration,
332 progress: &tokio::sync::Notify,
333 check: impl std::future::Future<Output = T>,
334) -> Option<T> {
335 tokio::pin!(check);
336 let deadline = tokio::time::sleep(max_wait);
337 tokio::pin!(deadline);
338 loop {
339 tokio::select! {
340 biased;
341 output = &mut check => return Some(output),
342 _ = &mut deadline => return None,
343 _ = progress.notified() => {}
344 _ = tokio::time::sleep(timeout) => return None,
345 }
346 }
347}
348
349pub async fn start_health_check_manager(
351 drt: DistributedRuntime,
352 config: Option<HealthCheckConfig>,
353) -> anyhow::Result<()> {
354 let config = config.unwrap_or_default();
355 let manager = Arc::new(HealthCheckManager::new(drt, config));
356
357 manager.start().await?;
359
360 Ok(())
361}
362
363pub async fn get_health_check_status(
365 drt: &DistributedRuntime,
366) -> anyhow::Result<serde_json::Value> {
367 let endpoint_subjects: Vec<String> = drt.system_health().lock().get_health_check_endpoints();
369
370 let mut endpoint_statuses = HashMap::new();
371
372 {
374 let system_health = drt.system_health();
375 let system_health_lock = system_health.lock();
376 for endpoint_subject in &endpoint_subjects {
377 let health_status = system_health_lock
378 .get_endpoint_health_status(endpoint_subject)
379 .unwrap_or(HealthStatus::NotReady);
380
381 let is_healthy = matches!(health_status, HealthStatus::Ready);
382
383 endpoint_statuses.insert(
384 endpoint_subject.clone(),
385 serde_json::json!({
386 "healthy": is_healthy,
387 "status": format!("{:?}", health_status),
388 }),
389 );
390 }
391 }
392
393 let overall_healthy = endpoint_statuses
394 .values()
395 .all(|v| v["healthy"].as_bool().unwrap_or(false));
396
397 Ok(serde_json::json!({
398 "status": if overall_healthy { "ready" } else { "notready" },
399 "endpoints_checked": endpoint_subjects.len(),
400 "endpoint_statuses": endpoint_statuses,
401 }))
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407 use tokio::sync::Notify;
408 use tokio::time::Instant;
409
410 const TIMEOUT: Duration = Duration::from_secs(3);
411 const MAX_WAIT: Duration = Duration::from_secs(60);
412
413 fn engine_progress(passes: u32) -> Arc<Notify> {
415 let progress = Arc::new(Notify::new());
416 let engine = progress.clone();
417 tokio::spawn(async move {
418 for _ in 0..passes {
419 tokio::time::sleep(Duration::from_secs(2)).await;
420 engine.notify_one();
421 }
422 });
423 progress
424 }
425
426 async fn unanswered(progress: &Notify) -> Duration {
427 let start = Instant::now();
428 let check = std::future::pending::<()>();
429 assert_eq!(
430 timeout_unless_progress(TIMEOUT, MAX_WAIT, progress, check).await,
431 None
432 );
433 start.elapsed()
434 }
435
436 #[tokio::test(start_paused = true)]
437 async fn check_without_progress_times_out() {
438 assert_eq!(unanswered(&Notify::new()).await, TIMEOUT);
439 }
440
441 #[tokio::test(start_paused = true)]
444 async fn check_outlasts_the_timeout_while_the_engine_makes_progress() {
445 let progress = engine_progress(10);
446 let check = async {
447 tokio::time::sleep(Duration::from_secs(15)).await;
448 "answered"
449 };
450
451 let result = timeout_unless_progress(TIMEOUT, MAX_WAIT, &progress, check).await;
452
453 assert_eq!(result, Some("answered"));
454 }
455
456 #[tokio::test(start_paused = true)]
458 async fn check_times_out_once_progress_stops() {
459 let progress = engine_progress(10);
460
461 assert_eq!(
462 unanswered(&progress).await,
463 Duration::from_secs(20) + TIMEOUT
464 );
465 }
466
467 #[tokio::test(start_paused = true)]
469 async fn check_times_out_at_the_cap_despite_progress() {
470 let progress = engine_progress(u32::MAX);
471
472 assert_eq!(unanswered(&progress).await, MAX_WAIT);
473 }
474}
475
476#[cfg(all(test, feature = "integration"))]
482mod push_handler_notify_tests {
483 use super::*;
484 use crate::component::{Instance, TransportType};
485 use crate::config::HealthStatus;
486 use crate::distributed::distributed_test_utils::create_test_drt_async;
487 use crate::engine::{AsyncEngine, AsyncEngineContextProvider};
488 use crate::local_endpoint_registry::LocalAsyncEngine;
489 use crate::pipeline::network::codec::{TwoPartCodec, TwoPartMessage};
490 use crate::pipeline::network::{
491 ConnectionInfo, Ingress, PushWorkHandler, quic_response::QuicResponseServer,
492 };
493 use crate::pipeline::{ManyOut, ResponseStream, SingleIn};
494 use crate::protocols::annotated::Annotated;
495 use async_trait::async_trait;
496 use bytes::Bytes;
497 use futures::stream;
498 use std::sync::Arc;
499 use std::time::Duration;
500
501 type TestRequest = serde_json::Value;
502 type TestResponse = Annotated<serde_json::Value>;
503
504 struct MockStreamingEngine {
508 num_chunks: usize,
509 error_indices: Vec<usize>,
511 }
512
513 impl MockStreamingEngine {
514 fn success(num_chunks: usize) -> Arc<Self> {
515 Arc::new(Self {
516 num_chunks,
517 error_indices: vec![],
518 })
519 }
520
521 fn all_errors(num_chunks: usize) -> Arc<Self> {
522 Arc::new(Self {
523 num_chunks,
524 error_indices: (0..num_chunks).collect(),
525 })
526 }
527
528 fn with_error_at(num_chunks: usize, error_indices: Vec<usize>) -> Arc<Self> {
529 Arc::new(Self {
530 num_chunks,
531 error_indices,
532 })
533 }
534 }
535
536 #[async_trait]
537 impl AsyncEngine<SingleIn<TestRequest>, ManyOut<TestResponse>, anyhow::Error>
538 for MockStreamingEngine
539 {
540 async fn generate(
541 &self,
542 input: SingleIn<TestRequest>,
543 ) -> anyhow::Result<ManyOut<TestResponse>> {
544 let (_data, ctx) = input.into_parts();
545 let chunks: Vec<TestResponse> = (0..self.num_chunks)
546 .map(|i| {
547 if self.error_indices.contains(&i) {
548 Annotated::from_error(format!("mock error at chunk {i}"))
549 } else {
550 Annotated::from_data(serde_json::json!({"token": i}))
551 }
552 })
553 .collect();
554 Ok(ResponseStream::new(
555 Box::pin(stream::iter(chunks)),
556 ctx.context(),
557 ))
558 }
559 }
560
561 fn encode_request(
563 request_id: &str,
564 connection_info: ConnectionInfo,
565 request_body: &serde_json::Value,
566 ) -> Bytes {
567 let control = serde_json::json!({
568 "id": request_id,
569 "request_type": "single_in",
570 "response_type": "many_out",
571 "connection_info": connection_info,
572 });
573 let header = serde_json::to_vec(&control).unwrap();
574 let data = serde_json::to_vec(request_body).unwrap();
575 let msg = TwoPartMessage::new(Bytes::from(header), Bytes::from(data));
576 TwoPartCodec::default().encode_message(msg).unwrap()
577 }
578
579 async fn setup_quic_receiver(
582 request_id: &str,
583 ) -> (
584 Arc<QuicResponseServer>,
585 ConnectionInfo,
586 crate::pipeline::network::StreamProvider<crate::pipeline::network::StreamReceiver>,
587 ) {
588 let shutdown = crate::CancellationToken::new();
589 let address = "127.0.0.1:0".parse().unwrap();
590 let server = QuicResponseServer::new(address, address, shutdown).unwrap();
591 let context = crate::pipeline::Context::with_id_and_metadata(
592 (),
593 request_id.to_string(),
594 Default::default(),
595 );
596 let registered = server.register_response(context.context());
597 let (connection_info, provider) = registered.into_parts();
598
599 (server, connection_info, provider)
600 }
601
602 fn register_endpoint(
605 drt: &crate::DistributedRuntime,
606 endpoint_name: &str,
607 local_engine: LocalAsyncEngine,
608 ) -> Arc<tokio::sync::Notify> {
609 let payload = serde_json::json!({
610 "prompt": "health",
611 "_health_check": true
612 });
613 drt.system_health().lock().register_health_check_target(
614 endpoint_name,
615 Instance {
616 component: "test_component".to_string(),
617 endpoint: endpoint_name.to_string(),
618 namespace: "test_namespace".to_string(),
619 instance_id: 0,
620 transport: TransportType::Nats(endpoint_name.to_string()),
621 device_type: None,
622 request_plane_codec: None,
623 },
624 payload,
625 );
626
627 drt.local_endpoint_registry()
628 .register(endpoint_name.to_string(), local_engine);
629
630 drt.system_health()
631 .lock()
632 .get_endpoint_health_check_notifier(endpoint_name)
633 .expect("Notifier should exist for registered endpoint")
634 }
635
636 async fn send_request(ingress: &Ingress<SingleIn<TestRequest>, ManyOut<TestResponse>>) {
638 let request_id = uuid::Uuid::new_v4().to_string();
639 let (_server, connection_info, _provider) = setup_quic_receiver(&request_id).await;
640 let payload = encode_request(
641 &request_id,
642 connection_info,
643 &serde_json::json!({"prompt": "test"}),
644 );
645 let result = ingress.handle_payload(payload, Some(request_id)).await;
646 assert!(result.is_ok(), "handle_payload should succeed");
647 }
648
649 fn assert_status(
651 drt: &crate::DistributedRuntime,
652 endpoint_name: &str,
653 expected: HealthStatus,
654 msg: &str,
655 ) {
656 let status = drt
657 .system_health()
658 .lock()
659 .get_endpoint_health_status(endpoint_name);
660 assert_eq!(status, Some(expected), "{msg}");
661 }
662
663 fn create_ingress(
665 _drt: &crate::DistributedRuntime,
666 engine: Arc<MockStreamingEngine>,
667 notifier: Arc<tokio::sync::Notify>,
668 ) -> Arc<Ingress<SingleIn<TestRequest>, ManyOut<TestResponse>>> {
669 let ingress =
670 Ingress::<SingleIn<TestRequest>, ManyOut<TestResponse>>::for_engine(engine).unwrap();
671 ingress
672 .set_endpoint_health_check_notifier(notifier)
673 .unwrap();
674 ingress
675 .set_quic_response_client_pool(
676 crate::pipeline::network::quic_response::process_client_pool_from_env().unwrap(),
677 )
678 .unwrap();
679 ingress
680 }
681
682 async fn start_manager(drt: &crate::DistributedRuntime, canary_wait_ms: u64) {
684 let config = HealthCheckConfig {
685 canary_wait_time: Duration::from_millis(canary_wait_ms),
686 request_timeout: Duration::from_secs(1),
687 };
688 let manager = Arc::new(HealthCheckManager::new(drt.clone(), config));
689 manager.start().await.unwrap();
690 }
691
692 #[tokio::test]
697 async fn test_successful_streaming_sets_ready() {
698 let drt = create_test_drt_async().await;
699 let endpoint = "test.successful_streaming";
700
701 let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
702 assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
703
704 let ingress = create_ingress(&drt, MockStreamingEngine::success(5), notifier);
705 start_manager(&drt, 500).await;
706
707 send_request(&ingress).await;
708 tokio::time::sleep(Duration::from_millis(200)).await;
709
710 assert_status(
712 &drt,
713 endpoint,
714 HealthStatus::Ready,
715 "successful streaming should set Ready via notification path",
716 );
717 }
718
719 #[tokio::test]
723 async fn test_canary_fires_on_idle_engine() {
724 let drt = create_test_drt_async().await;
725 let endpoint = "test.canary_idle";
726
727 let _notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::success(1));
728 assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
729
730 start_manager(&drt, 50).await;
731 tokio::time::sleep(Duration::from_millis(300)).await;
732
733 assert_status(
735 &drt,
736 endpoint,
737 HealthStatus::Ready,
738 "canary should fire and set Ready on idle engine",
739 );
740 }
741
742 #[tokio::test]
746 async fn test_error_streaming_stays_not_ready() {
747 let drt = create_test_drt_async().await;
748 let endpoint = "test.error_streaming";
749
750 let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
751 assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
752
753 let ingress = create_ingress(&drt, MockStreamingEngine::all_errors(3), notifier);
755 start_manager(&drt, 50).await;
756
757 send_request(&ingress).await;
758 tokio::time::sleep(Duration::from_millis(300)).await;
760
761 assert_status(
763 &drt,
764 endpoint,
765 HealthStatus::NotReady,
766 "error streaming should not notify, canary also errors — stays NotReady",
767 );
768 }
769
770 #[tokio::test]
774 async fn test_idle_engine_with_failing_canary() {
775 let drt = create_test_drt_async().await;
776 let endpoint = "test.canary_fails";
777
778 let _notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
779 assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
780
781 start_manager(&drt, 50).await;
782 tokio::time::sleep(Duration::from_millis(300)).await;
783
784 assert_status(
786 &drt,
787 endpoint,
788 HealthStatus::NotReady,
789 "canary fired but engine errored, status stays NotReady",
790 );
791 }
792
793 #[tokio::test]
799 async fn test_mixed_streaming_sets_ready() {
800 let drt = create_test_drt_async().await;
801 let endpoint = "test.mixed_streaming";
802
803 let notifier = register_endpoint(&drt, endpoint, MockStreamingEngine::all_errors(1));
804 assert_status(&drt, endpoint, HealthStatus::NotReady, "initial");
805
806 let ingress = create_ingress(
808 &drt,
809 MockStreamingEngine::with_error_at(5, vec![4]),
810 notifier,
811 );
812 start_manager(&drt, 500).await;
813
814 send_request(&ingress).await;
815 tokio::time::sleep(Duration::from_millis(200)).await;
816
817 assert_status(
819 &drt,
820 endpoint,
821 HealthStatus::Ready,
822 "successful chunks should set Ready despite trailing error",
823 );
824 }
825}
826
827#[cfg(all(test, feature = "integration"))]
831mod integration_tests {
832 use super::*;
833 use crate::distributed::distributed_test_utils::create_test_drt_async;
834 use std::sync::Arc;
835 use std::time::Duration;
836
837 #[tokio::test]
838 async fn test_initialization() {
839 let drt = create_test_drt_async().await;
840
841 let canary_wait_time = Duration::from_secs(5);
842 let request_timeout = Duration::from_secs(3);
843
844 let config = HealthCheckConfig {
845 canary_wait_time,
846 request_timeout,
847 };
848
849 let manager = HealthCheckManager::new(drt.clone(), config);
850
851 assert_eq!(manager.config.canary_wait_time, canary_wait_time);
852 assert_eq!(manager.config.request_timeout, request_timeout);
853 }
854
855 #[tokio::test]
856 async fn test_payload_registration() {
857 let drt = create_test_drt_async().await;
858
859 let endpoint = "test.endpoint";
860 let payload = serde_json::json!({
861 "prompt": "test",
862 "_health_check": true
863 });
864
865 drt.system_health().lock().register_health_check_target(
866 endpoint,
867 crate::component::Instance {
868 component: "test_component".to_string(),
869 endpoint: "test_endpoint".to_string(),
870 namespace: "test_namespace".to_string(),
871 instance_id: 12345,
872 transport: crate::component::TransportType::Nats(endpoint.to_string()),
873 device_type: None,
874 request_plane_codec: None,
875 },
876 payload.clone(),
877 );
878
879 let retrieved = drt
880 .system_health()
881 .lock()
882 .get_health_check_target(endpoint)
883 .map(|t| t.payload);
884 assert!(retrieved.is_some());
885 assert_eq!(retrieved.unwrap(), payload);
886
887 let endpoints = drt.system_health().lock().get_health_check_endpoints();
889 assert!(endpoints.contains(&endpoint.to_string()));
890 }
891
892 #[tokio::test]
893 async fn test_spawn_per_endpoint_tasks() {
894 let drt = create_test_drt_async().await;
895
896 for i in 0..3 {
897 let endpoint = format!("test.endpoint.{}", i);
898 let payload = serde_json::json!({
899 "prompt": format!("test{}", i),
900 "_health_check": true
901 });
902 drt.system_health().lock().register_health_check_target(
903 &endpoint,
904 crate::component::Instance {
905 component: "test_component".to_string(),
906 endpoint: format!("test_endpoint_{}", i),
907 namespace: "test_namespace".to_string(),
908 instance_id: i,
909 transport: crate::component::TransportType::Nats(endpoint.clone()),
910 device_type: None,
911 request_plane_codec: None,
912 },
913 payload,
914 );
915 }
916
917 let config = HealthCheckConfig {
918 canary_wait_time: Duration::from_secs(5),
919 request_timeout: Duration::from_secs(1),
920 };
921
922 let manager = Arc::new(HealthCheckManager::new(drt.clone(), config));
923 manager.clone().start().await.unwrap();
924
925 let tasks = manager.endpoint_tasks.lock();
927 assert_eq!(tasks.len(), 3);
929 let endpoints: Vec<String> = tasks.keys().cloned().collect();
931 assert!(endpoints.contains(&"test.endpoint.0".to_string()));
932 assert!(endpoints.contains(&"test.endpoint.1".to_string()));
933 assert!(endpoints.contains(&"test.endpoint.2".to_string()));
934 }
935
936 #[tokio::test]
937 async fn test_endpoint_health_check_notifier_created() {
938 let drt = create_test_drt_async().await;
939
940 let endpoint = "test.endpoint.notifier";
941 let payload = serde_json::json!({
942 "prompt": "test",
943 "_health_check": true
944 });
945
946 drt.system_health().lock().register_health_check_target(
948 endpoint,
949 crate::component::Instance {
950 component: "test_component".to_string(),
951 endpoint: "test_endpoint_notifier".to_string(),
952 namespace: "test_namespace".to_string(),
953 instance_id: 999,
954 transport: crate::component::TransportType::Nats(endpoint.to_string()),
955 device_type: None,
956 request_plane_codec: None,
957 },
958 payload.clone(),
959 );
960
961 let notifier = drt
963 .system_health()
964 .lock()
965 .get_endpoint_health_check_notifier(endpoint);
966
967 assert!(
968 notifier.is_some(),
969 "Endpoint should have a notifier created"
970 );
971
972 if let Some(notifier) = notifier {
974 notifier.notify_one();
975 }
976
977 let status = drt
979 .system_health()
980 .lock()
981 .get_endpoint_health_status(endpoint);
982 assert_eq!(status, Some(HealthStatus::NotReady));
983 }
984}