Skip to main content

minco_plugin_health/
lib.rs

1//! Default health plugin and asynchronous health registry.
2#![forbid(unsafe_code)]
3
4use async_trait::async_trait;
5use minco_core::{
6    CapabilityProvision, HealthCheckDescriptor, Plugin, PluginContext, PluginDescriptor,
7    PluginError, PluginFinalizeContext, PluginId, PluginStability,
8};
9use semver::{Version, VersionReq};
10use serde::{Deserialize, Serialize};
11use std::sync::{Arc, RwLock};
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct HealthResult {
15    pub id: String,
16    pub ready: bool,
17    pub critical: bool,
18    pub detail: Option<String>,
19}
20
21#[async_trait]
22pub trait HealthCheck: Send + Sync + std::fmt::Debug {
23    fn id(&self) -> &str;
24
25    fn critical(&self) -> bool {
26        true
27    }
28
29    async fn check(&self) -> HealthResult;
30}
31
32#[derive(Default)]
33pub struct HealthRegistry {
34    checks: RwLock<Vec<Arc<dyn HealthCheck>>>,
35}
36
37impl std::fmt::Debug for HealthRegistry {
38    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        formatter
40            .debug_struct("HealthRegistry")
41            .finish_non_exhaustive()
42    }
43}
44
45impl HealthRegistry {
46    pub fn register_now(&self, check: Arc<dyn HealthCheck>) {
47        self.checks
48            .write()
49            .unwrap_or_else(std::sync::PoisonError::into_inner)
50            .push(check);
51    }
52
53    pub fn register(&self, check: Arc<dyn HealthCheck>) {
54        self.register_now(check);
55    }
56
57    pub async fn run(&self) -> Vec<HealthResult> {
58        let checks = self
59            .checks
60            .read()
61            .unwrap_or_else(std::sync::PoisonError::into_inner)
62            .clone();
63        let mut results = Vec::with_capacity(checks.len());
64        for check in checks {
65            results.push(check.check().await);
66        }
67        results
68    }
69
70    pub async fn ready(&self) -> bool {
71        self.run()
72            .await
73            .into_iter()
74            .all(|result| result.ready || !result.critical)
75    }
76
77    #[must_use]
78    pub fn len(&self) -> usize {
79        self.checks
80            .read()
81            .unwrap_or_else(std::sync::PoisonError::into_inner)
82            .len()
83    }
84
85    #[must_use]
86    pub fn is_empty(&self) -> bool {
87        self.len() == 0
88    }
89}
90
91#[derive(Debug, Clone)]
92pub struct StaticHealthCheck {
93    id: String,
94    ready: bool,
95    critical: bool,
96}
97
98impl StaticHealthCheck {
99    #[must_use]
100    pub fn new(id: impl Into<String>, ready: bool, critical: bool) -> Self {
101        Self {
102            id: id.into(),
103            ready,
104            critical,
105        }
106    }
107}
108
109#[async_trait]
110impl HealthCheck for StaticHealthCheck {
111    fn id(&self) -> &str {
112        &self.id
113    }
114
115    fn critical(&self) -> bool {
116        self.critical
117    }
118
119    async fn check(&self) -> HealthResult {
120        HealthResult {
121            id: self.id.clone(),
122            ready: self.ready,
123            critical: self.critical,
124            detail: None,
125        }
126    }
127}
128
129#[derive(Debug, Clone, Default)]
130pub struct HealthPlugin;
131
132impl Plugin for HealthPlugin {
133    fn descriptor(&self) -> PluginDescriptor {
134        let mut descriptor = PluginDescriptor::new(
135            PluginId::new("health").expect("static plugin ID"),
136            Version::new(1, 0, 0),
137            "Liveness, readiness, and dependency health registry",
138        );
139        descriptor.default_enabled = true;
140        descriptor.core_compatibility =
141            VersionReq::parse(concat!("^", env!("CARGO_PKG_VERSION"))).expect("package version");
142        descriptor.stability = PluginStability::Stable;
143        descriptor.documentation = Some("https://docs.rs/minco-plugin-health".into());
144        descriptor.provides.push(CapabilityProvision {
145            name: "health.registry".into(),
146            version: Version::new(1, 0, 0),
147        });
148        descriptor.health_checks.push(HealthCheckDescriptor {
149            id: "minco-core".into(),
150            critical: true,
151        });
152        descriptor
153    }
154
155    fn install(&self, context: &mut PluginContext<'_>) -> Result<(), PluginError> {
156        let registry = Arc::new(HealthRegistry::default());
157        registry.register_now(Arc::new(StaticHealthCheck::new("minco-core", true, true)));
158        context.services().insert(registry)?;
159        Ok(())
160    }
161
162    fn finalize(&self, context: &mut PluginFinalizeContext<'_>) -> Result<(), PluginError> {
163        let registry = context.services().get::<HealthRegistry>()?;
164        for check in context.contributions().get_shared::<dyn HealthCheck>() {
165            registry.register_now(check);
166        }
167        Ok(())
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use minco_core::{PluginManager, PluginSelection};
175
176    #[tokio::test]
177    async fn readiness_fails_only_for_critical_failures() {
178        let registry = HealthRegistry::default();
179        registry.register(Arc::new(StaticHealthCheck::new("optional", false, false)));
180        assert!(registry.ready().await);
181        registry.register(Arc::new(StaticHealthCheck::new("database", false, true)));
182        assert!(!registry.ready().await);
183    }
184
185    #[test]
186    fn health_plugin_aggregates_shared_health_contributions_during_finalize() {
187        #[derive(Debug)]
188        struct ContributingPlugin;
189
190        impl Plugin for ContributingPlugin {
191            fn descriptor(&self) -> PluginDescriptor {
192                let mut descriptor = PluginDescriptor::new(
193                    PluginId::new("contributor").unwrap(),
194                    Version::new(1, 0, 0),
195                    "health contributor",
196                );
197                descriptor
198                    .plugin_dependencies
199                    .push(PluginId::new("health").unwrap());
200                descriptor
201            }
202
203            fn install(&self, context: &mut PluginContext<'_>) -> Result<(), PluginError> {
204                context
205                    .contributions()
206                    .push_shared::<dyn HealthCheck>(Arc::new(StaticHealthCheck::new(
207                        "contributed",
208                        true,
209                        true,
210                    )));
211                Ok(())
212            }
213        }
214
215        let mut manager = PluginManager::default();
216        manager.register(HealthPlugin).unwrap();
217        manager.register(ContributingPlugin).unwrap();
218        let mut selection = PluginSelection::default();
219        selection
220            .enabled
221            .insert(PluginId::new("contributor").unwrap());
222        let application = manager.compose(&selection).unwrap();
223        let registry = application.services.get::<HealthRegistry>().unwrap();
224        assert_eq!(registry.len(), 2);
225    }
226}