ipfrs-storage 0.1.0

Storage backends and block management for IPFRS content-addressed system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Health check system for storage backends
//!
//! Provides standardized health checks for all storage backends including:
//! - Liveness checks (is the service running?)
//! - Readiness checks (can the service handle requests?)
//! - Detailed status reporting
//! - Aggregate health across multiple backends
//!
//! ## Example
//! ```no_run
//! use ipfrs_storage::{HealthChecker, HealthStatus};
//!
//! #[tokio::main]
//! async fn main() {
//!     let checker = HealthChecker::new();
//!
//!     let status = checker.check_liveness().await;
//!     println!("Health: {:?}", status);
//! }
//! ```

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Health status of a component
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HealthStatus {
    /// Component is healthy and operational
    Healthy,
    /// Component is degraded but operational
    Degraded,
    /// Component is unhealthy and not operational
    Unhealthy,
}

impl HealthStatus {
    /// Check if status is healthy
    pub fn is_healthy(&self) -> bool {
        matches!(self, HealthStatus::Healthy)
    }

    /// Check if status is degraded
    pub fn is_degraded(&self) -> bool {
        matches!(self, HealthStatus::Degraded)
    }

    /// Check if status is unhealthy
    pub fn is_unhealthy(&self) -> bool {
        matches!(self, HealthStatus::Unhealthy)
    }

    /// Check if component can serve requests (healthy or degraded)
    pub fn is_ready(&self) -> bool {
        !self.is_unhealthy()
    }
}

/// Detailed health check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckResult {
    /// Overall status
    pub status: HealthStatus,
    /// Component name
    pub component: String,
    /// Human-readable message
    pub message: String,
    /// When the check was performed
    pub checked_at: String,
    /// Check duration
    pub duration_ms: u64,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl HealthCheckResult {
    /// Create a healthy result
    pub fn healthy(component: String, message: String, duration: Duration) -> Self {
        Self {
            status: HealthStatus::Healthy,
            component,
            message,
            checked_at: chrono::Utc::now().to_rfc3339(),
            duration_ms: duration.as_millis() as u64,
            metadata: HashMap::new(),
        }
    }

    /// Create a degraded result
    pub fn degraded(component: String, message: String, duration: Duration) -> Self {
        Self {
            status: HealthStatus::Degraded,
            component,
            message,
            checked_at: chrono::Utc::now().to_rfc3339(),
            duration_ms: duration.as_millis() as u64,
            metadata: HashMap::new(),
        }
    }

    /// Create an unhealthy result
    pub fn unhealthy(component: String, message: String, duration: Duration) -> Self {
        Self {
            status: HealthStatus::Unhealthy,
            component,
            message,
            checked_at: chrono::Utc::now().to_rfc3339(),
            duration_ms: duration.as_millis() as u64,
            metadata: HashMap::new(),
        }
    }

    /// Add metadata to the result
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }
}

/// Trait for health-checkable components
#[async_trait]
pub trait HealthCheck: Send + Sync {
    /// Perform a liveness check
    ///
    /// Liveness checks verify that the component is running.
    /// A failed liveness check indicates the component should be restarted.
    async fn check_liveness(&self) -> HealthCheckResult;

    /// Perform a readiness check
    ///
    /// Readiness checks verify that the component can handle requests.
    /// A failed readiness check means the component should not receive traffic.
    async fn check_readiness(&self) -> HealthCheckResult;

    /// Get component name
    fn component_name(&self) -> String;
}

/// Aggregate health checker for multiple components
pub struct HealthChecker {
    /// Registered health checks
    checks: Arc<parking_lot::RwLock<Vec<Arc<dyn HealthCheck>>>>,
}

impl HealthChecker {
    /// Create a new health checker
    pub fn new() -> Self {
        Self {
            checks: Arc::new(parking_lot::RwLock::new(Vec::new())),
        }
    }

    /// Register a health check
    pub fn register<H: HealthCheck + 'static>(&self, check: H) {
        self.checks.write().push(Arc::new(check));
    }

    /// Check liveness of all registered components
    pub async fn check_liveness(&self) -> AggregateHealthResult {
        let checks = self.checks.read().clone();
        let mut results = Vec::new();

        for check in checks {
            results.push(check.check_liveness().await);
        }

        AggregateHealthResult::from_results(results)
    }

    /// Check readiness of all registered components
    pub async fn check_readiness(&self) -> AggregateHealthResult {
        let checks = self.checks.read().clone();
        let mut results = Vec::new();

        for check in checks {
            results.push(check.check_readiness().await);
        }

        AggregateHealthResult::from_results(results)
    }

    /// Get detailed status of all components
    pub async fn detailed_status(&self) -> DetailedHealthStatus {
        let checks = self.checks.read().clone();
        let mut liveness_results = Vec::new();
        let mut readiness_results = Vec::new();

        for check in checks {
            liveness_results.push(check.check_liveness().await);
            readiness_results.push(check.check_readiness().await);
        }

        DetailedHealthStatus {
            liveness: AggregateHealthResult::from_results(liveness_results),
            readiness: AggregateHealthResult::from_results(readiness_results),
        }
    }
}

impl Default for HealthChecker {
    fn default() -> Self {
        Self::new()
    }
}

/// Aggregate health result across multiple components
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregateHealthResult {
    /// Overall status
    pub status: HealthStatus,
    /// Individual component results
    pub components: Vec<HealthCheckResult>,
    /// Total number of components
    pub total_components: usize,
    /// Number of healthy components
    pub healthy_count: usize,
    /// Number of degraded components
    pub degraded_count: usize,
    /// Number of unhealthy components
    pub unhealthy_count: usize,
}

impl AggregateHealthResult {
    /// Create aggregate result from individual results
    pub fn from_results(components: Vec<HealthCheckResult>) -> Self {
        let total_components = components.len();
        let mut healthy_count = 0;
        let mut degraded_count = 0;
        let mut unhealthy_count = 0;

        for result in &components {
            match result.status {
                HealthStatus::Healthy => healthy_count += 1,
                HealthStatus::Degraded => degraded_count += 1,
                HealthStatus::Unhealthy => unhealthy_count += 1,
            }
        }

        // Determine overall status
        let status = if unhealthy_count > 0 {
            HealthStatus::Unhealthy
        } else if degraded_count > 0 {
            HealthStatus::Degraded
        } else {
            HealthStatus::Healthy
        };

        Self {
            status,
            components,
            total_components,
            healthy_count,
            degraded_count,
            unhealthy_count,
        }
    }

    /// Check if all components are healthy
    pub fn all_healthy(&self) -> bool {
        self.status == HealthStatus::Healthy
    }

    /// Check if any component is unhealthy
    pub fn any_unhealthy(&self) -> bool {
        self.unhealthy_count > 0
    }

    /// Get unhealthy components
    pub fn unhealthy_components(&self) -> Vec<&HealthCheckResult> {
        self.components
            .iter()
            .filter(|r| r.status == HealthStatus::Unhealthy)
            .collect()
    }
}

/// Detailed health status with liveness and readiness
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetailedHealthStatus {
    /// Liveness check results
    pub liveness: AggregateHealthResult,
    /// Readiness check results
    pub readiness: AggregateHealthResult,
}

impl DetailedHealthStatus {
    /// Check if system is alive
    pub fn is_alive(&self) -> bool {
        self.liveness.status != HealthStatus::Unhealthy
    }

    /// Check if system is ready
    pub fn is_ready(&self) -> bool {
        self.readiness.status != HealthStatus::Unhealthy
    }
}

/// Simple health check implementation for testing
#[derive(Clone)]
pub struct SimpleHealthCheck {
    name: String,
    is_healthy: Arc<parking_lot::RwLock<bool>>,
}

impl SimpleHealthCheck {
    /// Create a new simple health check
    pub fn new(name: String) -> Self {
        Self {
            name,
            is_healthy: Arc::new(parking_lot::RwLock::new(true)),
        }
    }

    /// Set health status
    pub fn set_healthy(&self, healthy: bool) {
        *self.is_healthy.write() = healthy;
    }
}

#[async_trait]
impl HealthCheck for SimpleHealthCheck {
    async fn check_liveness(&self) -> HealthCheckResult {
        let start = Instant::now();
        let is_healthy = *self.is_healthy.read();
        let duration = start.elapsed();

        if is_healthy {
            HealthCheckResult::healthy(
                self.name.clone(),
                "Component is alive".to_string(),
                duration,
            )
        } else {
            HealthCheckResult::unhealthy(
                self.name.clone(),
                "Component is not alive".to_string(),
                duration,
            )
        }
    }

    async fn check_readiness(&self) -> HealthCheckResult {
        let start = Instant::now();
        let is_healthy = *self.is_healthy.read();
        let duration = start.elapsed();

        if is_healthy {
            HealthCheckResult::healthy(
                self.name.clone(),
                "Component is ready".to_string(),
                duration,
            )
        } else {
            HealthCheckResult::unhealthy(
                self.name.clone(),
                "Component is not ready".to_string(),
                duration,
            )
        }
    }

    fn component_name(&self) -> String {
        self.name.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_health_status() {
        assert!(HealthStatus::Healthy.is_healthy());
        assert!(!HealthStatus::Degraded.is_healthy());
        assert!(!HealthStatus::Unhealthy.is_healthy());

        assert!(HealthStatus::Healthy.is_ready());
        assert!(HealthStatus::Degraded.is_ready());
        assert!(!HealthStatus::Unhealthy.is_ready());
    }

    #[tokio::test]
    async fn test_simple_health_check() {
        let check = SimpleHealthCheck::new("test".to_string());

        let result = check.check_liveness().await;
        assert!(result.status.is_healthy());

        check.set_healthy(false);
        let result = check.check_liveness().await;
        assert!(result.status.is_unhealthy());
    }

    #[tokio::test]
    async fn test_health_checker_aggregate() {
        let checker = HealthChecker::new();

        let check1 = SimpleHealthCheck::new("component1".to_string());
        let check2 = SimpleHealthCheck::new("component2".to_string());

        checker.register(check1.clone());
        checker.register(check2.clone());

        let result = checker.check_liveness().await;
        assert!(result.all_healthy());
        assert_eq!(result.healthy_count, 2);

        // Make one component unhealthy
        check1.set_healthy(false);

        let result = checker.check_liveness().await;
        assert!(!result.all_healthy());
        assert!(result.any_unhealthy());
        assert_eq!(result.healthy_count, 1);
        assert_eq!(result.unhealthy_count, 1);
    }

    #[tokio::test]
    async fn test_detailed_status() {
        let checker = HealthChecker::new();
        let check = SimpleHealthCheck::new("test".to_string());
        checker.register(check);

        let status = checker.detailed_status().await;
        assert!(status.is_alive());
        assert!(status.is_ready());
    }

    #[tokio::test]
    async fn test_aggregate_health_result() {
        let results = vec![
            HealthCheckResult::healthy(
                "comp1".to_string(),
                "OK".to_string(),
                Duration::from_millis(10),
            ),
            HealthCheckResult::degraded(
                "comp2".to_string(),
                "Slow".to_string(),
                Duration::from_millis(100),
            ),
        ];

        let aggregate = AggregateHealthResult::from_results(results);
        assert_eq!(aggregate.status, HealthStatus::Degraded);
        assert_eq!(aggregate.healthy_count, 1);
        assert_eq!(aggregate.degraded_count, 1);
        assert_eq!(aggregate.unhealthy_count, 0);
    }
}