1use std::{
19 collections::{HashMap, HashSet},
20 sync::{Arc, OnceLock},
21 time::Instant,
22};
23use tokio::sync::mpsc;
24
25use crate::component;
26use crate::config::HealthStatus;
27use crate::metrics::{MetricsHierarchy, prometheus_names::distributed_runtime};
28
29pub struct ReadinessHold {
44 system_health: Arc<parking_lot::Mutex<SystemHealth>>,
45 endpoint: String,
46}
47
48impl ReadinessHold {
49 pub fn take(system_health: Arc<parking_lot::Mutex<SystemHealth>>, endpoint: &str) -> Self {
50 system_health.lock().hold_endpoint_readiness(endpoint);
51 Self {
52 system_health,
53 endpoint: endpoint.to_string(),
54 }
55 }
56}
57
58impl Drop for ReadinessHold {
59 fn drop(&mut self) {
60 self.system_health
61 .lock()
62 .release_endpoint_readiness(&self.endpoint);
63 }
64}
65
66#[derive(Clone, Debug)]
68pub struct HealthCheckTarget {
69 pub instance: component::Instance,
70 pub payload: serde_json::Value,
71}
72
73#[derive(Clone, Default)]
75struct EndpointNotifiers {
76 activity: Arc<tokio::sync::Notify>,
78 progress: Arc<tokio::sync::Notify>,
80}
81
82#[derive(Clone)]
87pub struct SystemHealth {
88 system_health: HealthStatus,
89 endpoint_health: Arc<std::sync::RwLock<HashMap<String, HealthStatus>>>,
90 health_check_targets: Arc<std::sync::RwLock<HashMap<String, HealthCheckTarget>>>,
92 health_check_notifiers: Arc<std::sync::RwLock<HashMap<String, EndpointNotifiers>>>,
94 readiness_holds: Arc<std::sync::RwLock<HashSet<String>>>,
97 new_endpoint_tx: mpsc::UnboundedSender<String>,
101 new_endpoint_rx: Arc<parking_lot::Mutex<Option<mpsc::UnboundedReceiver<String>>>>,
102 use_endpoint_health_status: Vec<String>,
103 health_check_enabled: bool,
104 health_path: String,
105 live_path: String,
106 start_time: Instant,
107 uptime_gauge: OnceLock<prometheus::Gauge>,
108}
109
110impl SystemHealth {
111 pub fn new(
112 starting_health_status: HealthStatus,
113 use_endpoint_health_status: Vec<String>,
114 health_check_enabled: bool,
115 health_path: String,
116 live_path: String,
117 ) -> Self {
118 let initial_endpoint_status = if health_check_enabled {
120 HealthStatus::NotReady
121 } else {
122 starting_health_status.clone()
123 };
124 let mut endpoint_health = HashMap::new();
125 for endpoint in &use_endpoint_health_status {
126 endpoint_health.insert(endpoint.clone(), initial_endpoint_status.clone());
127 }
128
129 let (tx, rx) = mpsc::unbounded_channel();
131
132 SystemHealth {
133 system_health: starting_health_status,
134 endpoint_health: Arc::new(std::sync::RwLock::new(endpoint_health)),
135 health_check_targets: Arc::new(std::sync::RwLock::new(HashMap::new())),
136 health_check_notifiers: Arc::new(std::sync::RwLock::new(HashMap::new())),
137 readiness_holds: Arc::new(std::sync::RwLock::new(HashSet::new())),
138 new_endpoint_tx: tx,
139 new_endpoint_rx: Arc::new(parking_lot::Mutex::new(Some(rx))),
140 use_endpoint_health_status,
141 health_check_enabled,
142 health_path,
143 live_path,
144 start_time: Instant::now(),
145 uptime_gauge: OnceLock::new(),
146 }
147 }
148
149 pub fn health_check_enabled(&self) -> bool {
150 self.health_check_enabled
151 }
152
153 pub fn set_endpoint_registered(&self, endpoint: &str) {
157 if self.readiness_holds.read().unwrap().contains(endpoint) {
158 return;
159 }
160 let has_health_check_target = self
161 .health_check_targets
162 .read()
163 .unwrap()
164 .contains_key(endpoint);
165 if !self.health_check_enabled || !has_health_check_target {
166 self.set_endpoint_health_status(endpoint, HealthStatus::Ready);
167 }
168 }
169
170 pub fn hold_endpoint_readiness(&self, endpoint: &str) {
187 self.readiness_holds
188 .write()
189 .unwrap()
190 .insert(endpoint.to_string());
191 }
192
193 pub fn release_endpoint_readiness(&self, endpoint: &str) {
198 self.readiness_holds.write().unwrap().remove(endpoint);
199 }
200
201 pub fn set_health_status(&mut self, status: HealthStatus) {
202 self.system_health = status;
203 }
204
205 pub fn set_endpoint_health_status(&self, endpoint: &str, status: HealthStatus) {
206 let mut endpoint_health = self.endpoint_health.write().unwrap();
207 endpoint_health.insert(endpoint.to_string(), status);
208 }
209
210 pub fn get_health_status(&self) -> (bool, HashMap<String, String>) {
213 let health_check_targets = self.health_check_targets.read().unwrap();
214 let endpoint_health = self.endpoint_health.read().unwrap();
215 let mut endpoints: HashMap<String, String> = HashMap::new();
216
217 for (endpoint, status) in endpoint_health.iter() {
218 endpoints.insert(
219 endpoint.clone(),
220 if *status == HealthStatus::Ready {
221 "ready".to_string()
222 } else {
223 "notready".to_string()
224 },
225 );
226 }
227
228 if !self.readiness_holds.read().unwrap().is_empty() {
232 return (false, endpoints);
233 }
234
235 let healthy = if !self.use_endpoint_health_status.is_empty() {
236 self.use_endpoint_health_status.iter().all(|endpoint| {
237 endpoint_health
238 .get(endpoint)
239 .is_some_and(|status| *status == HealthStatus::Ready)
240 })
241 } else {
242 if !health_check_targets.is_empty() {
244 health_check_targets
245 .iter()
246 .all(|(endpoint_subject, _target)| {
247 endpoint_health
248 .get(endpoint_subject)
249 .is_some_and(|status| *status == HealthStatus::Ready)
250 })
251 } else if self.health_check_enabled && !endpoint_health.is_empty() {
252 endpoint_health
256 .values()
257 .all(|status| *status == HealthStatus::Ready)
258 } else {
259 self.system_health == HealthStatus::Ready
261 }
262 };
263
264 (healthy, endpoints)
265 }
266
267 pub fn register_health_check_target(
269 &self,
270 endpoint_subject: &str,
271 instance: component::Instance,
272 payload: serde_json::Value,
273 ) {
274 let key = endpoint_subject.to_owned();
275
276 let inserted = {
278 let mut targets = self.health_check_targets.write().unwrap();
279 match targets.entry(key.clone()) {
280 std::collections::hash_map::Entry::Occupied(_) => false,
281 std::collections::hash_map::Entry::Vacant(v) => {
282 v.insert(HealthCheckTarget { instance, payload });
283 true
284 }
285 }
286 };
287
288 if !inserted {
289 tracing::warn!(
290 "Attempted to re-register health check for endpoint '{}'; ignoring.",
291 key
292 );
293 return;
294 }
295
296 {
298 let mut notifiers = self.health_check_notifiers.write().unwrap();
299 notifiers.entry(key.clone()).or_default();
300 }
301
302 {
304 let mut endpoint_health = self.endpoint_health.write().unwrap();
305 endpoint_health
306 .entry(key.clone())
307 .or_insert(HealthStatus::NotReady);
308 }
309
310 if let Err(e) = self.new_endpoint_tx.send(key.clone()) {
311 tracing::error!(
312 "Failed to send endpoint '{}' registration to health check manager: {}. \
313 Health checks will not be performed for this endpoint.",
314 key,
315 e
316 );
317 }
318 }
319
320 pub fn get_health_check_targets(&self) -> Vec<(String, HealthCheckTarget)> {
322 let targets = self.health_check_targets.read().unwrap();
323 targets
324 .iter()
325 .map(|(k, v)| (k.clone(), v.clone()))
326 .collect()
327 }
328
329 pub fn has_health_check_targets(&self) -> bool {
331 let targets = self.health_check_targets.read().unwrap();
332 !targets.is_empty()
333 }
334
335 pub fn get_health_check_endpoints(&self) -> Vec<String> {
337 let targets = self.health_check_targets.read().unwrap();
338 targets.keys().cloned().collect()
339 }
340
341 pub fn get_health_check_target(&self, endpoint: &str) -> Option<HealthCheckTarget> {
343 let targets = self.health_check_targets.read().unwrap();
344 targets.get(endpoint).cloned()
345 }
346
347 pub fn get_endpoint_health_status(&self, endpoint: &str) -> Option<HealthStatus> {
349 let endpoint_health = self.endpoint_health.read().unwrap();
350 endpoint_health.get(endpoint).cloned()
351 }
352
353 pub fn get_endpoint_health_check_notifier(
355 &self,
356 endpoint_subject: &str,
357 ) -> Option<Arc<tokio::sync::Notify>> {
358 let notifiers = self.health_check_notifiers.read().unwrap();
359 notifiers.get(endpoint_subject).map(|n| n.activity.clone())
360 }
361
362 pub fn get_endpoint_progress_notifier(
369 &self,
370 endpoint_subject: &str,
371 ) -> Option<Arc<tokio::sync::Notify>> {
372 let notifiers = self.health_check_notifiers.read().unwrap();
373 notifiers.get(endpoint_subject).map(|n| n.progress.clone())
374 }
375
376 pub fn take_new_endpoint_receiver(&self) -> Option<mpsc::UnboundedReceiver<String>> {
379 self.new_endpoint_rx.lock().take()
380 }
381
382 pub fn initialize_uptime_gauge<T: MetricsHierarchy>(&self, registry: &T) -> anyhow::Result<()> {
384 let gauge = registry.metrics().create_gauge(
385 distributed_runtime::UPTIME_SECONDS,
386 "Total uptime of the DistributedRuntime in seconds",
387 &[],
388 )?;
389 self.uptime_gauge
390 .set(gauge)
391 .map_err(|_| anyhow::anyhow!("uptime_gauge already initialized"))?;
392 Ok(())
393 }
394
395 pub fn uptime(&self) -> std::time::Duration {
397 self.start_time.elapsed()
398 }
399
400 pub fn update_uptime_gauge(&self) {
402 if let Some(gauge) = self.uptime_gauge.get() {
403 gauge.set(self.uptime().as_secs_f64());
404 }
405 }
406
407 pub fn health_path(&self) -> &str {
409 &self.health_path
410 }
411
412 pub fn live_path(&self) -> &str {
414 &self.live_path
415 }
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use crate::component::{Instance, TransportType};
422
423 const ENDPOINT: &str = "generate";
424
425 fn system_health(health_check_enabled: bool) -> SystemHealth {
426 SystemHealth::new(
427 HealthStatus::NotReady,
428 Vec::new(),
431 health_check_enabled,
432 "/health".to_string(),
433 "/live".to_string(),
434 )
435 }
436
437 fn instance() -> Instance {
438 Instance {
439 component: "backend".to_string(),
440 endpoint: ENDPOINT.to_string(),
441 namespace: "dynamo".to_string(),
442 instance_id: 1,
443 transport: TransportType::Tcp("127.0.0.1:0".to_string()),
444 device_type: None,
445 request_plane_codec: None,
446 }
447 }
448
449 #[test]
452 fn registered_target_makes_the_worker_ready_with_canary_off() {
453 let health = system_health(false);
454 health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
455 health.set_endpoint_registered(ENDPOINT);
456
457 let (healthy, endpoints) = health.get_health_status();
458 assert!(healthy, "a registered, ready endpoint must report healthy");
459 assert_eq!(endpoints.get(ENDPOINT).map(String::as_str), Some("ready"));
460 }
461
462 #[test]
474 fn ready_endpoint_without_a_registered_target_still_reports_unhealthy() {
475 let health = system_health(false);
476 health.set_endpoint_registered(ENDPOINT);
478
479 let (healthy, endpoints) = health.get_health_status();
480 assert_eq!(
481 endpoints.get(ENDPOINT).map(String::as_str),
482 Some("ready"),
483 "the endpoint itself is ready"
484 );
485 assert!(
486 !healthy,
487 "with no health-check target the endpoint's readiness is ignored and \
488 the worker falls back to system_health (NotReady) — this is the 503"
489 );
490 }
491
492 #[test]
495 fn held_endpoint_is_not_ready_on_transport_registration() {
496 let health = system_health(false);
497 health.hold_endpoint_readiness(ENDPOINT);
498 health.set_endpoint_registered(ENDPOINT);
499 assert_ne!(
500 health.get_endpoint_health_status(ENDPOINT),
501 Some(HealthStatus::Ready),
502 "a held endpoint must not be marked ready by transport registration"
503 );
504
505 health.release_endpoint_readiness(ENDPOINT);
506 health.set_endpoint_registered(ENDPOINT);
507 assert_eq!(
508 health.get_endpoint_health_status(ENDPOINT),
509 Some(HealthStatus::Ready),
510 "after release the owner's registration signal publishes readiness"
511 );
512 }
513
514 #[test]
520 fn an_unheld_sibling_endpoint_cannot_report_the_worker_ready() {
521 let health = system_health(true);
522 health.hold_endpoint_readiness(ENDPOINT);
523 health.set_endpoint_registered(ENDPOINT);
524 health.set_endpoint_registered("rl_system");
525
526 assert!(
527 !health.get_health_status().0,
528 "a held endpoint must keep the worker not-ready however many siblings register"
529 );
530
531 health.release_endpoint_readiness(ENDPOINT);
532 health.set_endpoint_registered(ENDPOINT);
533 assert!(health.get_health_status().0);
534 }
535
536 #[test]
540 fn a_hold_does_not_suppress_a_siblings_endpoint_flag() {
541 let health = system_health(false);
542 health.hold_endpoint_readiness(ENDPOINT);
543 health.set_endpoint_registered("other");
544 assert_eq!(
545 health.get_endpoint_health_status("other"),
546 Some(HealthStatus::Ready)
547 );
548 }
549
550 #[test]
553 fn without_targets_health_tracks_system_health_only() {
554 let mut health = system_health(false);
555 health.set_endpoint_registered(ENDPOINT);
556 assert!(!health.get_health_status().0);
557
558 health.set_health_status(HealthStatus::Ready);
559 assert!(
560 health.get_health_status().0,
561 "with no targets, system_health alone decides"
562 );
563 }
564
565 #[test]
568 fn payloadless_endpoint_is_ready_with_canary_on() {
569 let health = system_health(true);
570 health.set_endpoint_registered(ENDPOINT);
571
572 let (healthy, endpoints) = health.get_health_status();
573 assert!(
574 healthy,
575 "a registered payload-less endpoint must report healthy"
576 );
577 assert_eq!(endpoints.get(ENDPOINT).map(String::as_str), Some("ready"));
578 }
579
580 #[test]
586 fn canary_enabled_withholds_ready_until_verified() {
587 let health = system_health(true);
588 health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
589 health.set_endpoint_registered(ENDPOINT);
590
591 assert!(
592 !health.get_health_status().0,
593 "canary must verify before the worker reports ready"
594 );
595
596 health.set_endpoint_health_status(ENDPOINT, HealthStatus::Ready);
597 assert!(
598 health.get_health_status().0,
599 "after the canary marks it ready the worker is healthy"
600 );
601 }
602
603 #[test]
606 fn engine_progress_does_not_notify_activity() {
607 use futures::FutureExt;
608
609 let health = system_health(true);
610 assert!(health.get_endpoint_progress_notifier(ENDPOINT).is_none());
611
612 health.register_health_check_target(ENDPOINT, instance(), serde_json::json!({}));
613 let activity = health.get_endpoint_health_check_notifier(ENDPOINT).unwrap();
614 let progress = health.get_endpoint_progress_notifier(ENDPOINT).unwrap();
615
616 progress.notify_one();
617 assert!(activity.notified().now_or_never().is_none());
618 assert!(progress.notified().now_or_never().is_some());
619 }
620}