1use std::future::Future;
4#[cfg(test)]
5use std::sync::atomic::AtomicUsize;
6use std::{
7 collections::HashSet,
8 sync::{
9 atomic::{AtomicBool, Ordering::Relaxed},
10 Arc, Mutex,
11 },
12 time::Duration,
13};
14
15use futures::StreamExt as _;
16use saluki_error::{generic_error, GenericError};
17use saluki_metrics::{static_metrics, Gauge, Histogram};
18use tokio::{pin, time::Instant};
19use tokio::{
20 select,
21 sync::{
22 mpsc::{self, error::TrySendError},
23 Notify,
24 },
25};
26use tokio_util::time::{delay_queue::Key, DelayQueue};
27use tracing::{debug, info, trace};
28
29use crate::support::SubsystemIdentifier;
30
31mod api;
32pub use self::api::HealthAPIHandler;
33
34mod worker;
35pub use self::worker::HealthRegistryWorker;
36
37const DEFAULT_PROBE_TIMEOUT_DUR: Duration = Duration::from_secs(5);
38const DEFAULT_PROBE_BACKOFF_DUR: Duration = Duration::from_secs(1);
39
40pub struct Health {
42 shared: Arc<SharedComponentState>,
43 liveness: Option<LivenessChannel>,
44 readiness_notify: Arc<Notify>,
45}
46
47impl Health {
48 pub fn mark_ready(&mut self) {
50 self.update_readiness(true);
51 }
52
53 pub fn mark_not_ready(&mut self) {
55 self.update_readiness(false);
56 }
57
58 fn update_readiness(&self, ready: bool) {
59 self.shared.ready.store(ready, Relaxed);
60 self.shared.telemetry.update_readiness(ready);
61
62 if ready {
64 self.readiness_notify.notify_waiters();
65 }
66 }
67
68 pub async fn live(&mut self) {
76 match self.liveness.as_mut() {
77 Some(channel) => {
78 channel.respond().await;
79 }
80 None => std::future::pending().await,
81 }
82 }
83
84 pub(crate) fn take_liveness_responder(&mut self) -> Option<LivenessResponder> {
91 self.liveness.take().map(|channel| LivenessResponder { channel })
92 }
93}
94
95struct LivenessChannel {
97 request_rx: mpsc::Receiver<LivenessRequest>,
98 response_tx: mpsc::Sender<LivenessResponse>,
99}
100
101impl LivenessChannel {
102 async fn respond(&mut self) -> bool {
106 match self.request_rx.recv().await {
107 Some(request) => {
108 let response = request.into_response();
109 let _ = self.response_tx.send(response).await;
110 true
111 }
112 None => false,
113 }
114 }
115}
116
117pub(crate) struct LivenessResponder {
134 channel: LivenessChannel,
135}
136
137impl LivenessResponder {
138 pub(crate) async fn drive<F: Future>(mut self, fut: F) -> F::Output {
143 pin!(fut);
144
145 loop {
146 select! {
147 biased;
150
151 open = self.channel.respond() => {
152 if !open {
153 return fut.await;
155 }
156 },
157 output = &mut fut => return output,
158 }
159 }
160 }
161}
162
163#[derive(Clone, Copy, Eq, PartialEq)]
164enum HealthState {
165 Live,
166 Unknown,
167 Dead,
168}
169
170#[static_metrics(prefix = health, labels(component_id))]
171#[derive(Clone)]
172struct Telemetry {
173 component_ready: Gauge,
174 component_live: Gauge,
175 #[metric(level = trace)]
176 component_liveness_latency_seconds: Histogram,
177}
178
179impl Telemetry {
180 fn from_name(name: &SubsystemIdentifier) -> Self {
181 Self::new(name)
182 }
183
184 fn update_readiness(&self, ready: bool) {
185 self.component_ready().set(if ready { 1.0 } else { 0.0 });
186 }
187
188 fn update_liveness(&self, state: HealthState, response_latency: Duration) {
189 let live = match state {
190 HealthState::Live => 1.0,
191 HealthState::Unknown => 0.0,
192 HealthState::Dead => -1.0,
193 };
194
195 self.component_live().set(live);
196 self.component_liveness_latency_seconds()
197 .record(response_latency.as_secs_f64());
198 }
199}
200
201struct SharedComponentState {
202 ready: AtomicBool,
203 telemetry: Telemetry,
204}
205
206struct ComponentState {
207 name: SubsystemIdentifier,
208 health: HealthState,
209 shared: Arc<SharedComponentState>,
210 request_tx: mpsc::Sender<LivenessRequest>,
211 last_response: Instant,
212 last_response_latency: Duration,
213}
214
215impl ComponentState {
216 fn new(
217 name: SubsystemIdentifier, response_tx: mpsc::Sender<LivenessResponse>, readiness_notify: Arc<Notify>,
218 ) -> (Self, Health) {
219 let shared = Arc::new(SharedComponentState {
220 ready: AtomicBool::new(false),
221 telemetry: Telemetry::from_name(&name),
222 });
223 let (request_tx, request_rx) = mpsc::channel(1);
224
225 let state = Self {
226 name,
227 health: HealthState::Unknown,
228 shared: Arc::clone(&shared),
229 request_tx,
230 last_response: Instant::now(),
231 last_response_latency: Duration::from_secs(0),
232 };
233
234 let handle = Health {
235 shared,
236 liveness: Some(LivenessChannel {
237 request_rx,
238 response_tx,
239 }),
240 readiness_notify,
241 };
242
243 (state, handle)
244 }
245
246 fn is_ready(&self) -> bool {
247 self.shared.ready.load(Relaxed) && self.health != HealthState::Dead
252 }
253
254 fn is_live(&self) -> bool {
255 self.health == HealthState::Live
256 }
257
258 fn mark_live(&mut self, response_sent: Instant, response_latency: Duration) {
259 self.health = HealthState::Live;
260 self.last_response = response_sent;
261 self.last_response_latency = response_latency;
262 self.shared.telemetry.update_liveness(self.health, response_latency);
263 }
264
265 fn mark_not_live(&mut self) {
266 self.health = HealthState::Unknown;
267
268 self.shared
270 .telemetry
271 .update_liveness(self.health, DEFAULT_PROBE_TIMEOUT_DUR);
272 }
273
274 fn mark_dead(&mut self) {
275 self.health = HealthState::Dead;
276
277 self.shared
279 .telemetry
280 .update_liveness(self.health, DEFAULT_PROBE_TIMEOUT_DUR);
281 }
282}
283
284struct LivenessRequest {
285 component_id: usize,
286 timeout_key: Key,
287 request_sent: Instant,
288}
289
290impl LivenessRequest {
291 fn new(component_id: usize, timeout_key: Key) -> Self {
292 Self {
293 component_id,
294 timeout_key,
295 request_sent: Instant::now(),
296 }
297 }
298
299 fn into_response(self) -> LivenessResponse {
300 LivenessResponse {
301 request: self,
302 response_sent: Instant::now(),
303 }
304 }
305}
306
307struct LivenessResponse {
308 request: LivenessRequest,
309 response_sent: Instant,
310}
311
312enum HealthUpdate {
313 Alive {
314 last_response: Instant,
315 last_response_latency: Duration,
316 },
317 Unknown,
318 Dead,
319}
320
321impl HealthUpdate {
322 fn as_str(&self) -> &'static str {
323 match self {
324 HealthUpdate::Alive { .. } => "alive",
325 HealthUpdate::Unknown => "unknown",
326 HealthUpdate::Dead => "dead",
327 }
328 }
329}
330
331struct RegistryState {
332 registered_components: HashSet<SubsystemIdentifier>,
333 component_state: Vec<ComponentState>,
334 responses_tx: mpsc::Sender<LivenessResponse>,
335 responses_rx: Option<mpsc::Receiver<LivenessResponse>>,
336 pending_components: Vec<usize>,
337 pending_components_notify: Arc<Notify>,
338 readiness_notify: Arc<Notify>,
339}
340
341impl RegistryState {
342 fn new() -> Self {
343 let (responses_tx, responses_rx) = mpsc::channel(16);
344
345 Self {
346 registered_components: HashSet::new(),
347 component_state: Vec::new(),
348 responses_tx,
349 responses_rx: Some(responses_rx),
350 pending_components: Vec::new(),
351 pending_components_notify: Arc::new(Notify::new()),
352 readiness_notify: Arc::new(Notify::new()),
353 }
354 }
355}
356
357#[derive(Clone)]
375pub struct HealthRegistry {
376 inner: Arc<Mutex<RegistryState>>,
377}
378
379impl HealthRegistry {
380 pub fn new() -> Self {
382 Self {
383 inner: Arc::new(Mutex::new(RegistryState::new())),
384 }
385 }
386
387 #[cfg(test)]
388 fn state(&self) -> Arc<Mutex<RegistryState>> {
389 Arc::clone(&self.inner)
390 }
391
392 pub fn register_component(&self, id: &SubsystemIdentifier) -> Option<Health> {
398 let mut inner = self.inner.lock().unwrap();
399
400 if !inner.registered_components.insert(id.clone()) {
402 return None;
403 }
404
405 let readiness_notify = Arc::clone(&inner.readiness_notify);
407 let (state, handle) = ComponentState::new(id.clone(), inner.responses_tx.clone(), readiness_notify);
408 let component_id = inner.component_state.len();
409 inner.component_state.push(state);
410
411 debug!(component_id, "Registered component '{}'.", id);
412
413 inner.pending_components.push(component_id);
415 inner.pending_components_notify.notify_one();
416
417 Some(handle)
418 }
419
420 pub fn api_handler(&self) -> HealthAPIHandler {
425 HealthAPIHandler::from_state(Arc::clone(&self.inner))
426 }
427
428 pub async fn all_ready(&self) {
436 self.all_ready_matching(|_| true).await
437 }
438
439 pub async fn all_ready_matching<F>(&self, predicate: F)
449 where
450 F: Fn(&SubsystemIdentifier) -> bool,
451 {
452 let readiness_notify = {
453 let inner = self.inner.lock().unwrap();
454 Arc::clone(&inner.readiness_notify)
455 };
456
457 loop {
458 let notified = readiness_notify.notified();
460
461 if self.check_ready_matching(&predicate) {
462 return;
463 }
464
465 notified.await;
466 }
467 }
468
469 pub async fn all_ready_under(&self, root: SubsystemIdentifier) {
476 self.all_ready_matching(move |id| root.is_ancestor_of(id)).await
477 }
478
479 fn check_ready_matching<F>(&self, predicate: &F) -> bool
480 where
481 F: Fn(&SubsystemIdentifier) -> bool,
482 {
483 let inner = self.inner.lock().unwrap();
484 inner
485 .component_state
486 .iter()
487 .filter(|component| predicate(&component.name))
488 .all(|component| component.is_ready())
489 }
490
491 pub fn snapshot_json(&self) -> String {
498 #[derive(serde::Serialize)]
499 struct ComponentSnapshot {
500 live: bool,
501 ready: bool,
502 }
503
504 let inner = self.inner.lock().unwrap();
505 let mut state: std::collections::HashMap<String, ComponentSnapshot> = std::collections::HashMap::new();
506 for component in &inner.component_state {
507 state.insert(
508 component.name.to_string(),
509 ComponentSnapshot {
510 live: component.is_live(),
511 ready: component.is_ready(),
512 },
513 );
514 }
515 serde_json::to_string_pretty(&state).unwrap_or_else(|e| format!("{{\"error\": \"{e}\"}}"))
516 }
517
518 pub fn worker(&self) -> HealthRegistryWorker {
523 HealthRegistryWorker::new(self.clone())
524 }
525
526 pub(crate) fn into_runner(self) -> Result<Runner, GenericError> {
527 let (responses_rx, pending_components_notify) = {
529 let mut inner = self.inner.lock().unwrap();
530 let responses_rx = match inner.responses_rx.take() {
531 Some(rx) => rx,
532 None => return Err(generic_error!("health registry already spawned")),
533 };
534
535 let pending_components_notify = Arc::clone(&inner.pending_components_notify);
536 (responses_rx, pending_components_notify)
537 };
538
539 Ok(Runner::new(self.inner, responses_rx, pending_components_notify))
540 }
541}
542
543struct RunnerGuard {
549 registry: Arc<Mutex<RegistryState>>,
550 responses_rx: Option<mpsc::Receiver<LivenessResponse>>,
551}
552
553impl Drop for RunnerGuard {
554 fn drop(&mut self) {
555 if let Some(rx) = self.responses_rx.take() {
556 let mut inner = self.registry.lock().expect("registry state poisoned");
557 inner.responses_rx = Some(rx);
558 debug!("Returned response receiver to registry state.");
559 }
560 }
561}
562
563#[cfg(test)]
564struct RunnerState {
565 pending_scheduled_probes: AtomicUsize,
566 pending_probe_timeouts: AtomicUsize,
567}
568
569#[cfg(test)]
570impl RunnerState {
571 fn new() -> Self {
572 Self {
573 pending_scheduled_probes: AtomicUsize::new(0),
574 pending_probe_timeouts: AtomicUsize::new(0),
575 }
576 }
577
578 fn pending_scheduled_probes(&self) -> usize {
579 self.pending_scheduled_probes.load(Relaxed)
580 }
581
582 fn pending_probe_timeouts(&self) -> usize {
583 self.pending_probe_timeouts.load(Relaxed)
584 }
585
586 fn increment_pending_scheduled_probes(&self) {
587 self.pending_scheduled_probes.fetch_add(1, Relaxed);
588 }
589
590 fn increment_pending_probe_timeouts(&self) {
591 self.pending_probe_timeouts.fetch_add(1, Relaxed);
592 }
593
594 fn decrement_pending_scheduled_probes(&self) {
595 self.pending_scheduled_probes.fetch_sub(1, Relaxed);
596 }
597
598 fn decrement_pending_probe_timeouts(&self) {
599 self.pending_probe_timeouts.fetch_sub(1, Relaxed);
600 }
601}
602
603pub(super) struct Runner {
604 registry: Arc<Mutex<RegistryState>>,
605 pending_probes: DelayQueue<usize>,
606 pending_timeouts: DelayQueue<usize>,
607 guard: RunnerGuard,
608 pending_components_notify: Arc<Notify>,
609 #[cfg(test)]
610 state: Arc<RunnerState>,
611}
612
613impl Runner {
614 fn new(
615 registry: Arc<Mutex<RegistryState>>, responses_rx: mpsc::Receiver<LivenessResponse>,
616 pending_components_notify: Arc<Notify>,
617 ) -> Self {
618 #[cfg(test)]
619 let state = Arc::new(RunnerState::new());
620
621 let guard = RunnerGuard {
622 registry: Arc::clone(®istry),
623 responses_rx: Some(responses_rx),
624 };
625
626 Self {
627 registry,
628 pending_probes: DelayQueue::new(),
629 pending_timeouts: DelayQueue::new(),
630 guard,
631 pending_components_notify,
632 #[cfg(test)]
633 state,
634 }
635 }
636
637 #[cfg(test)]
638 fn state(&self) -> Arc<RunnerState> {
639 Arc::clone(&self.state)
640 }
641
642 fn drain_pending_components(&mut self) -> Vec<usize> {
643 let mut registry = self.registry.lock().unwrap();
645 registry.pending_components.drain(..).collect()
646 }
647
648 fn send_component_probe_request(&mut self, component_id: usize) -> Option<HealthUpdate> {
649 let mut registry = self.registry.lock().unwrap();
650 let component_state = &mut registry.component_state[component_id];
651
652 if component_state.request_tx.is_closed() {
654 debug!(component_name = %component_state.name, "Component is dead, skipping liveness probe.");
655 return Some(HealthUpdate::Dead);
656 }
657
658 trace!(component_name = %component_state.name, probe_timeout = ?DEFAULT_PROBE_TIMEOUT_DUR, "Sending liveness probe to component.");
659
660 let timeout_key = self.pending_timeouts.insert(component_id, DEFAULT_PROBE_TIMEOUT_DUR);
665
666 #[cfg(test)]
667 self.state.increment_pending_probe_timeouts();
668
669 let request = LivenessRequest::new(component_id, timeout_key);
670 if let Err(TrySendError::Closed(request)) = component_state.request_tx.try_send(request) {
671 debug!(component_name = %component_state.name, "Component is dead, removing pending timeout.");
672
673 self.pending_timeouts.remove(&request.timeout_key);
679
680 #[cfg(test)]
681 self.state.decrement_pending_probe_timeouts();
682
683 return Some(HealthUpdate::Dead);
684 }
685
686 None
687 }
688
689 fn schedule_probe_for_component(&mut self, component_id: usize, duration: Duration) {
690 #[cfg(test)]
691 self.state.increment_pending_scheduled_probes();
692
693 self.pending_probes.insert(component_id, duration);
694 }
695
696 fn schedule_all_existing_components(&mut self, responses_rx: &mut mpsc::Receiver<LivenessResponse>) {
697 let _pending = self.drain_pending_components();
700
701 while let Ok(response) = responses_rx.try_recv() {
706 self.handle_component_probe_response(response);
707 }
708
709 let (component_count, stale_component_ids) = {
713 let registry = self.registry.lock().unwrap();
714 let now = Instant::now();
715 let stale_ids: Vec<usize> = (0..registry.component_state.len())
716 .filter(|&id| {
717 let last = registry.component_state[id].last_response;
718 saluki_antithesis::always_or_unreachable!(
719 now >= last,
720 "health probe last-response clock did not move backward"
721 );
722 now.saturating_duration_since(last) >= DEFAULT_PROBE_TIMEOUT_DUR
723 })
724 .collect();
725 (registry.component_state.len(), stale_ids)
726 };
727
728 for &component_id in &stale_component_ids {
730 self.process_component_health_update(component_id, HealthUpdate::Unknown);
731 }
732
733 for component_id in 0..component_count {
735 self.schedule_probe_for_component(component_id, Duration::ZERO);
736 }
737
738 if component_count > 0 {
739 let fresh_count = component_count - stale_component_ids.len();
740 debug!(
741 component_count,
742 fresh_count,
743 stale_count = stale_component_ids.len(),
744 "Scheduled probes for all existing components."
745 );
746 }
747 }
748
749 fn handle_component_probe_response(&mut self, response: LivenessResponse) {
750 let component_id = response.request.component_id;
751 let timeout_key = response.request.timeout_key;
752 let request_sent = response.request.request_sent;
753 let response_sent = response.response_sent;
754 let response_latency = response_sent.checked_duration_since(request_sent).unwrap_or_default();
755
756 let timeout_was_pending = self.pending_timeouts.try_remove(&timeout_key).is_some();
758 if !timeout_was_pending {
759 let mut registry = self.registry.lock().unwrap();
760 let component_state = &mut registry.component_state[component_id];
761
762 debug!(component_name = %component_state.name, "Received probe response for component that already timed out.");
763 }
764
765 let update = HealthUpdate::Alive {
767 last_response: response_sent,
768 last_response_latency: response_latency,
769 };
770 self.process_component_health_update(component_id, update);
771
772 if timeout_was_pending {
775 #[cfg(test)]
776 self.state.decrement_pending_probe_timeouts();
777
778 self.schedule_probe_for_component(component_id, DEFAULT_PROBE_BACKOFF_DUR);
779 }
780 }
781
782 fn handle_component_timeout(&mut self, component_id: usize) {
783 self.process_component_health_update(component_id, HealthUpdate::Unknown);
785
786 self.schedule_probe_for_component(component_id, DEFAULT_PROBE_BACKOFF_DUR);
788 }
789
790 fn process_component_health_update(&mut self, component_id: usize, update: HealthUpdate) {
791 let mut registry = self.registry.lock().unwrap();
793 let component_state = &mut registry.component_state[component_id];
794 trace!(component_name = %component_state.name, status = update.as_str(), "Updating component health status.");
795
796 match update {
797 HealthUpdate::Alive {
798 last_response,
799 last_response_latency,
800 } => component_state.mark_live(last_response, last_response_latency),
801 HealthUpdate::Unknown => component_state.mark_not_live(),
802 HealthUpdate::Dead => component_state.mark_dead(),
803 }
804 }
805
806 async fn run<F: Future<Output = ()>>(mut self, shutdown: F) {
807 info!("Health checker running.");
808
809 let mut responses_rx = self
812 .guard
813 .responses_rx
814 .take()
815 .expect("responses_rx should always be Some when Runner is created");
816
817 self.schedule_all_existing_components(&mut responses_rx);
821
822 pin!(shutdown);
824
825 loop {
826 select! {
827 _ = &mut shutdown => {
829 info!("Health checker shutting down.");
830 break;
831 },
832
833 Some(entry) = self.pending_probes.next() => {
835 #[cfg(test)]
836 self.state.decrement_pending_scheduled_probes();
837
838 let component_id = entry.into_inner();
839 if let Some(health_update) = self.send_component_probe_request(component_id) {
840 self.process_component_health_update(component_id, health_update);
843 }
844 },
845
846 Some(entry) = self.pending_timeouts.next() => {
848 #[cfg(test)]
849 self.state.decrement_pending_probe_timeouts();
850
851 let component_id = entry.into_inner();
852 self.handle_component_timeout(component_id);
853 },
854
855 Some(response) = responses_rx.recv() => {
857 self.handle_component_probe_response(response);
858 },
859
860 _ = self.pending_components_notify.notified() => {
862 let pending_component_ids = self.drain_pending_components();
864 for pending_component_id in pending_component_ids {
865 self.process_component_health_update(pending_component_id, HealthUpdate::Unknown);
866 self.schedule_probe_for_component(pending_component_id, Duration::ZERO);
867 }
868 },
869 }
870 }
871
872 self.guard.responses_rx = Some(responses_rx);
874
875 }
878}
879
880#[cfg(test)]
881mod tests {
882 use std::future::Future;
883
884 use futures::FutureExt as _;
885 use saluki_metrics::test::TestRecorder;
886 use tokio::sync::oneshot;
887 use tokio_test::{
888 assert_pending, assert_ready,
889 task::{spawn, Spawn},
890 };
891
892 use super::*;
893
894 const COMPONENT_ID: &str = "test_component";
895
896 #[track_caller]
897 fn initialize_registry_with_component(
898 component_id: &str,
899 ) -> (
900 Health,
901 Spawn<impl Future<Output = ()>>,
902 Arc<Mutex<RegistryState>>,
903 Arc<RunnerState>,
904 ) {
905 let registry = HealthRegistry::new();
906 let registry_state = registry.state();
907
908 let handle = registry
910 .register_component(&SubsystemIdentifier::from_dotted(component_id))
911 .unwrap();
912
913 let runner = registry.into_runner().expect("should not fail to create runner");
917 let runner_state = runner.state();
918
919 let shutdown = std::future::pending();
921 let registry_task = spawn(runner.run(shutdown));
922
923 (handle, registry_task, registry_state, runner_state)
924 }
925
926 #[track_caller]
927 fn drive_until_quiesced<F: Future<Output = ()>>(task: &mut Spawn<F>) {
928 assert_pending!(task.poll());
929 while task.is_woken() {
930 assert_pending!(task.poll());
931 }
932 }
933
934 fn component_live(state: &Mutex<RegistryState>, component_id: &str) -> bool {
935 let state = state.lock().unwrap();
936 let target = SubsystemIdentifier::from_dotted(component_id);
937 state
938 .component_state
939 .iter()
940 .find(|state| state.name == target)
941 .map(|state| state.is_live())
942 .unwrap()
943 }
944
945 #[test]
946 fn basic_registration() {
947 let registry = HealthRegistry::new();
948 assert!(registry
949 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
950 .is_some());
951 }
952
953 #[test]
954 fn duplicate_component_registration_fails() {
955 let registry = HealthRegistry::new();
956
957 assert!(registry
959 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
960 .is_some());
961 assert!(registry
962 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
963 .is_none());
964 }
965
966 #[test]
967 fn duplicate_runner_creation_fails_while_running() {
968 let registry = HealthRegistry::new();
969 let registry2 = registry.clone();
970
971 let _runner = registry.into_runner().expect("first runner creation should succeed");
974
975 assert!(registry2.into_runner().is_err());
977 }
978
979 #[tokio::test]
980 async fn registry_can_be_respawned_after_shutdown() {
981 let registry = HealthRegistry::new();
982 let registry2 = registry.clone();
983 let registry3 = registry.clone();
984
985 let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
987 let runner = registry.into_runner().expect("first runner creation should succeed");
988
989 let join_handle = tokio::spawn(runner.run(shutdown_rx.map(|_| ())));
991
992 let _ = shutdown_tx.send(());
994
995 join_handle.await.expect("runner should complete without panic");
997
998 let _runner2 = registry2
1000 .into_runner()
1001 .expect("should be able to create runner after shutdown");
1002
1003 assert!(
1005 registry3.into_runner().is_err(),
1006 "should not be able to create runner while one exists"
1007 );
1008 }
1009
1010 #[test]
1011 fn readiness() {
1012 let registry = HealthRegistry::new();
1013
1014 let mut all_ready_fut = spawn(registry.all_ready());
1016 assert_ready!(all_ready_fut.poll());
1017
1018 let mut handle = registry
1020 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1021 .unwrap();
1022
1023 let mut all_ready_fut = spawn(registry.all_ready());
1024 assert_pending!(all_ready_fut.poll());
1025
1026 handle.mark_ready();
1028
1029 assert!(all_ready_fut.is_woken());
1030 assert_ready!(all_ready_fut.poll());
1031
1032 let mut all_ready_fut = spawn(registry.all_ready());
1034 assert_ready!(all_ready_fut.poll());
1035
1036 handle.mark_not_ready();
1038
1039 let mut all_ready_fut = spawn(registry.all_ready());
1040 assert_pending!(all_ready_fut.poll());
1041 }
1042
1043 #[test]
1044 fn readiness_telemetry_tracks_component_ready_gauge() {
1045 let recorder = TestRecorder::default();
1048 let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1049
1050 let registry = HealthRegistry::new();
1052 let mut handle = registry
1053 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1054 .unwrap();
1055
1056 let ready_gauge = || recorder.gauge((Telemetry::component_ready_name(), &[("component_id", COMPONENT_ID)]));
1057
1058 assert_eq!(ready_gauge(), Some(0.0));
1060
1061 handle.mark_ready();
1062 assert_eq!(ready_gauge(), Some(1.0));
1063
1064 handle.mark_not_ready();
1065 assert_eq!(ready_gauge(), Some(0.0));
1066 }
1067
1068 #[tokio::test(start_paused = true)]
1069 async fn liveness_telemetry_records_live_gauge_and_latency_histogram() {
1070 let recorder = TestRecorder::default();
1073 let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1074
1075 let registry = HealthRegistry::new();
1077 let registry_state = registry.state();
1078 let mut handle = registry
1079 .register_component(&SubsystemIdentifier::from_dotted(COMPONENT_ID))
1080 .unwrap();
1081 let runner = registry.into_runner().expect("should not fail to create runner");
1082 let mut registry_task = spawn(runner.run(std::future::pending::<()>()));
1083
1084 let live_gauge = || recorder.gauge((Telemetry::component_live_name(), &[("component_id", COMPONENT_ID)]));
1085 let latency_samples = || {
1086 recorder.histogram((
1087 Telemetry::component_liveness_latency_seconds_name(),
1088 &[("component_id", COMPONENT_ID)],
1089 ))
1090 };
1091
1092 let mut live_future = spawn(handle.live());
1094 assert_pending!(live_future.poll());
1095 drive_until_quiesced(&mut registry_task);
1096
1097 assert!(!component_live(®istry_state, COMPONENT_ID));
1099 assert_eq!(live_gauge(), Some(0.0));
1100 assert_eq!(latency_samples(), Some(Vec::new()));
1101
1102 assert!(live_future.is_woken());
1104 assert_ready!(live_future.poll());
1105 assert!(registry_task.is_woken());
1106 drive_until_quiesced(&mut registry_task);
1107
1108 assert!(component_live(®istry_state, COMPONENT_ID));
1109 assert_eq!(live_gauge(), Some(1.0));
1110
1111 let samples = latency_samples().expect("liveness latency histogram should be registered");
1113 assert_eq!(
1114 samples.len(),
1115 1,
1116 "handling one probe response must record exactly one liveness latency sample"
1117 );
1118 assert!(samples[0] >= 0.0, "recorded liveness latency must be non-negative");
1119 }
1120
1121 #[tokio::test(start_paused = true)]
1122 async fn component_responds_before_timeout() {
1123 let (mut handle, mut registry, registry_state, runner_state) = initialize_registry_with_component(COMPONENT_ID);
1125
1126 let mut live_future = spawn(handle.live());
1129 assert_pending!(live_future.poll());
1130 assert_eq!(runner_state.pending_probe_timeouts(), 0);
1131 assert_eq!(runner_state.pending_scheduled_probes(), 0);
1132
1133 drive_until_quiesced(&mut registry);
1135 assert_eq!(runner_state.pending_probe_timeouts(), 1);
1136 assert_eq!(runner_state.pending_scheduled_probes(), 0);
1137
1138 assert!(!component_live(®istry_state, COMPONENT_ID));
1140
1141 assert!(live_future.is_woken());
1145 assert_ready!(live_future.poll());
1146
1147 assert!(registry.is_woken());
1151 drive_until_quiesced(&mut registry);
1152
1153 assert!(component_live(®istry_state, COMPONENT_ID));
1154
1155 assert_eq!(runner_state.pending_probe_timeouts(), 0);
1158 assert_eq!(runner_state.pending_scheduled_probes(), 1);
1159 }
1160
1161 #[tokio::test(start_paused = true)]
1162 async fn component_responds_after_timeout() {
1163 let (mut handle, mut registry, registry_state, runner_state) = initialize_registry_with_component(COMPONENT_ID);
1165
1166 let mut live_future = spawn(handle.live());
1169 assert_pending!(live_future.poll());
1170 assert_eq!(runner_state.pending_probe_timeouts(), 0);
1171 assert_eq!(runner_state.pending_scheduled_probes(), 0);
1172
1173 drive_until_quiesced(&mut registry);
1175 assert_eq!(runner_state.pending_probe_timeouts(), 1);
1176 assert_eq!(runner_state.pending_scheduled_probes(), 0);
1177
1178 assert!(!component_live(®istry_state, COMPONENT_ID));
1180
1181 assert!(live_future.is_woken());
1185 assert!(!registry.is_woken());
1186
1187 tokio::time::advance(DEFAULT_PROBE_TIMEOUT_DUR + Duration::from_secs(1)).await;
1188
1189 assert!(registry.is_woken());
1193 drive_until_quiesced(&mut registry);
1194
1195 assert!(!component_live(®istry_state, COMPONENT_ID));
1196
1197 assert_eq!(runner_state.pending_probe_timeouts(), 0);
1200 assert_eq!(runner_state.pending_scheduled_probes(), 1);
1201
1202 assert_ready!(live_future.poll());
1204
1205 assert!(registry.is_woken());
1206 drive_until_quiesced(&mut registry);
1207
1208 assert!(component_live(®istry_state, COMPONENT_ID));
1209
1210 assert_eq!(runner_state.pending_probe_timeouts(), 0);
1213 assert_eq!(runner_state.pending_scheduled_probes(), 1);
1214 }
1215
1216 #[track_caller]
1217 #[allow(clippy::type_complexity)]
1218 fn initialize_registry_with_component_and_shutdown(
1219 component_id: &str,
1220 ) -> (
1221 Health,
1222 Spawn<impl Future<Output = ()>>,
1223 Arc<Mutex<RegistryState>>,
1224 Arc<RunnerState>,
1225 oneshot::Sender<()>,
1226 ) {
1227 let registry = HealthRegistry::new();
1228 let registry_state = registry.state();
1229 let handle = registry
1230 .register_component(&SubsystemIdentifier::from_dotted(component_id))
1231 .unwrap();
1232 let runner = registry.into_runner().expect("should not fail to create runner");
1233 let runner_state = runner.state();
1234
1235 let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
1236 let registry_task = spawn(runner.run(shutdown_rx.map(|_| ())));
1237
1238 (handle, registry_task, registry_state, runner_state, shutdown_tx)
1239 }
1240
1241 #[tokio::test(start_paused = true)]
1242 async fn respawn_preserves_fresh_component_health() {
1243 let (mut handle, mut registry, registry_state, _runner_state, shutdown_tx) =
1245 initialize_registry_with_component_and_shutdown(COMPONENT_ID);
1246 drive_until_quiesced(&mut registry);
1247
1248 let mut live_future = spawn(handle.live());
1250 assert_ready!(live_future.poll());
1251 drive_until_quiesced(&mut registry);
1252 assert!(component_live(®istry_state, COMPONENT_ID));
1253
1254 let _ = shutdown_tx.send(());
1256 assert_ready!(registry.poll());
1257
1258 let registry = HealthRegistry {
1260 inner: Arc::clone(®istry_state),
1261 };
1262 let runner = registry
1263 .into_runner()
1264 .expect("should be able to respawn after shutdown");
1265 let _runner_state = runner.state();
1266 let mut registry = spawn(runner.run(std::future::pending()));
1267 drive_until_quiesced(&mut registry);
1268
1269 assert!(component_live(®istry_state, COMPONENT_ID));
1271 }
1272
1273 #[tokio::test(start_paused = true)]
1274 async fn respawn_resets_stale_component_health() {
1275 let (mut handle, mut registry, registry_state, _runner_state, shutdown_tx) =
1277 initialize_registry_with_component_and_shutdown(COMPONENT_ID);
1278 drive_until_quiesced(&mut registry);
1279
1280 let mut live_future = spawn(handle.live());
1282 assert_ready!(live_future.poll());
1283 drive_until_quiesced(&mut registry);
1284 assert!(component_live(®istry_state, COMPONENT_ID));
1285
1286 let _ = shutdown_tx.send(());
1288 assert_ready!(registry.poll());
1289
1290 tokio::time::advance(DEFAULT_PROBE_TIMEOUT_DUR + Duration::from_secs(1)).await;
1292
1293 let registry = HealthRegistry {
1295 inner: Arc::clone(®istry_state),
1296 };
1297 let runner = registry
1298 .into_runner()
1299 .expect("should be able to respawn after shutdown");
1300 let _runner_state = runner.state();
1301 let mut registry = spawn(runner.run(std::future::pending()));
1302 drive_until_quiesced(&mut registry);
1303
1304 assert!(!component_live(®istry_state, COMPONENT_ID));
1306 }
1307
1308 fn component_dead(state: &Mutex<RegistryState>, component_id: &str) -> bool {
1309 let state = state.lock().unwrap();
1310 let target = SubsystemIdentifier::from_dotted(component_id);
1311 state
1312 .component_state
1313 .iter()
1314 .find(|state| state.name == target)
1315 .map(|state| state.health == HealthState::Dead)
1316 .unwrap()
1317 }
1318
1319 #[tokio::test(start_paused = true)]
1320 async fn live_never_resolves_after_responder_is_taken() {
1321 let (mut handle, mut registry, _registry_state, _runner_state) =
1322 initialize_registry_with_component(COMPONENT_ID);
1323 let _responder = handle.take_liveness_responder().expect("responder should be present");
1324 assert!(handle.take_liveness_responder().is_none());
1325
1326 drive_until_quiesced(&mut registry);
1328
1329 let mut live_future = spawn(handle.live());
1330 assert_pending!(live_future.poll());
1331 }
1332
1333 #[tokio::test(start_paused = true)]
1334 async fn responder_answers_probes_while_driven_future_waits() {
1335 let (mut handle, mut registry, registry_state, _runner_state) =
1336 initialize_registry_with_component(COMPONENT_ID);
1337 let responder = handle.take_liveness_responder().expect("responder should be present");
1338
1339 let (unblock_tx, unblock_rx) = oneshot::channel::<u32>();
1342 let mut driven = spawn(responder.drive(async move { unblock_rx.await.unwrap() }));
1343 assert_pending!(driven.poll());
1344
1345 drive_until_quiesced(&mut registry);
1347 assert!(!component_live(®istry_state, COMPONENT_ID));
1348
1349 assert!(driven.is_woken());
1350 assert_pending!(driven.poll());
1351
1352 assert!(registry.is_woken());
1353 drive_until_quiesced(&mut registry);
1354 assert!(component_live(®istry_state, COMPONENT_ID));
1355
1356 unblock_tx.send(42).unwrap();
1358 assert!(driven.is_woken());
1359 assert_eq!(assert_ready!(driven.poll()), 42);
1360 }
1361
1362 #[tokio::test(start_paused = true)]
1363 async fn component_is_dead_after_driven_future_completes() {
1364 let (mut handle, mut registry, registry_state, _runner_state) =
1365 initialize_registry_with_component(COMPONENT_ID);
1366 let responder = handle.take_liveness_responder().expect("responder should be present");
1367
1368 let mut driven = spawn(responder.drive(async {}));
1370 assert_ready!(driven.poll());
1371
1372 drive_until_quiesced(&mut registry);
1374 assert!(component_dead(®istry_state, COMPONENT_ID));
1375 drop(handle);
1376 }
1377}