tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use axum::{
    Json, Router,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Health check status
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unhealthy,
}

/// Health check result for a single component
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ComponentHealth {
    pub name: String,
    pub status: HealthStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Overall health check response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HealthResponse {
    pub status: HealthStatus,
    pub checks: Vec<ComponentHealth>,
}

impl IntoResponse for HealthResponse {
    fn into_response(self) -> Response {
        let status_code = match self.status {
            HealthStatus::Healthy => StatusCode::OK,
            HealthStatus::Degraded => StatusCode::OK,
            HealthStatus::Unhealthy => StatusCode::SERVICE_UNAVAILABLE,
        };

        (status_code, Json(self)).into_response()
    }
}

/// Trait for implementing health checks
pub trait HealthCheck: Send + Sync {
    fn name(&self) -> &str;
    fn check(
        &self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ComponentHealth> + Send + '_>>;
}

/// Basic health check that always returns healthy
#[derive(Debug, Clone, Copy, Default)]
pub struct BasicHealthCheck;

impl HealthCheck for BasicHealthCheck {
    fn name(&self) -> &str {
        "application"
    }

    fn check(
        &self,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ComponentHealth> + Send + '_>> {
        Box::pin(async {
            ComponentHealth {
                name: self.name().to_string(),
                status: HealthStatus::Healthy,
                message: Some("Application is running".to_string()),
            }
        })
    }
}

/// Health check manager that runs all registered checks
pub struct HealthChecker {
    checks: Vec<Arc<dyn HealthCheck>>,
}

impl HealthChecker {
    pub fn new() -> Self {
        Self {
            checks: vec![Arc::new(BasicHealthCheck)],
        }
    }

    pub fn with_check(mut self, check: Arc<dyn HealthCheck>) -> Self {
        self.checks.push(check);
        self
    }

    pub async fn check_health(&self) -> HealthResponse {
        let mut checks = Vec::new();
        let mut overall_status = HealthStatus::Healthy;

        for check in &self.checks {
            let result = check.check().await;

            match result.status {
                HealthStatus::Unhealthy => overall_status = HealthStatus::Unhealthy,
                HealthStatus::Degraded if overall_status == HealthStatus::Healthy => {
                    overall_status = HealthStatus::Degraded
                }
                _ => {}
            }

            checks.push(result);
        }

        HealthResponse {
            status: overall_status,
            checks,
        }
    }
}

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

/// Handler for the health endpoint
pub async fn health_handler() -> HealthResponse {
    let checker = HealthChecker::new();
    checker.check_health().await
}

/// Creates the health check router
pub fn health_routes() -> Router {
    Router::new().route("/health", get(health_handler))
}

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

    // ============ HealthStatus tests ============

    #[test]
    fn test_health_status_serialization() {
        assert_eq!(
            serde_json::to_string(&HealthStatus::Healthy).unwrap(),
            "\"healthy\""
        );
        assert_eq!(
            serde_json::to_string(&HealthStatus::Degraded).unwrap(),
            "\"degraded\""
        );
        assert_eq!(
            serde_json::to_string(&HealthStatus::Unhealthy).unwrap(),
            "\"unhealthy\""
        );
    }

    #[test]
    fn test_health_status_deserialization() {
        assert_eq!(
            serde_json::from_str::<HealthStatus>("\"healthy\"").unwrap(),
            HealthStatus::Healthy
        );
        assert_eq!(
            serde_json::from_str::<HealthStatus>("\"degraded\"").unwrap(),
            HealthStatus::Degraded
        );
        assert_eq!(
            serde_json::from_str::<HealthStatus>("\"unhealthy\"").unwrap(),
            HealthStatus::Unhealthy
        );
    }

    #[test]
    fn test_health_status_equality() {
        assert_eq!(HealthStatus::Healthy, HealthStatus::Healthy);
        assert_ne!(HealthStatus::Healthy, HealthStatus::Degraded);
        assert_ne!(HealthStatus::Healthy, HealthStatus::Unhealthy);
    }

    // ============ ComponentHealth tests ============

    #[test]
    fn test_component_health_creation() {
        let health = ComponentHealth {
            name: "database".to_string(),
            status: HealthStatus::Healthy,
            message: Some("Connected".to_string()),
        };

        assert_eq!(health.name, "database");
        assert_eq!(health.status, HealthStatus::Healthy);
        assert_eq!(health.message, Some("Connected".to_string()));
    }

    #[test]
    fn test_component_health_serialization_with_message() {
        let health = ComponentHealth {
            name: "cache".to_string(),
            status: HealthStatus::Degraded,
            message: Some("High latency".to_string()),
        };

        let json = serde_json::to_string(&health).unwrap();
        assert!(json.contains("\"name\":\"cache\""));
        assert!(json.contains("\"status\":\"degraded\""));
        assert!(json.contains("\"message\":\"High latency\""));
    }

    #[test]
    fn test_component_health_serialization_without_message() {
        let health = ComponentHealth {
            name: "service".to_string(),
            status: HealthStatus::Healthy,
            message: None,
        };

        let json = serde_json::to_string(&health).unwrap();
        assert!(json.contains("\"name\":\"service\""));
        assert!(json.contains("\"status\":\"healthy\""));
        // message should be skipped when None
        assert!(!json.contains("message"));
    }

    // ============ HealthResponse tests ============

    #[test]
    fn test_health_response_creation() {
        let response = HealthResponse {
            status: HealthStatus::Healthy,
            checks: vec![ComponentHealth {
                name: "app".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }],
        };

        assert_eq!(response.status, HealthStatus::Healthy);
        assert_eq!(response.checks.len(), 1);
    }

    #[test]
    fn test_health_response_serialization() {
        let response = HealthResponse {
            status: HealthStatus::Degraded,
            checks: vec![
                ComponentHealth {
                    name: "db".to_string(),
                    status: HealthStatus::Healthy,
                    message: None,
                },
                ComponentHealth {
                    name: "cache".to_string(),
                    status: HealthStatus::Degraded,
                    message: Some("Slow".to_string()),
                },
            ],
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("\"status\":\"degraded\""));
        assert!(json.contains("\"checks\""));
        assert!(json.contains("\"db\""));
        assert!(json.contains("\"cache\""));
    }

    #[tokio::test]
    async fn test_health_response_into_response_healthy() {
        let response = HealthResponse {
            status: HealthStatus::Healthy,
            checks: vec![],
        };

        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_health_response_into_response_degraded() {
        let response = HealthResponse {
            status: HealthStatus::Degraded,
            checks: vec![],
        };

        let http_response = response.into_response();
        // Degraded still returns 200 OK
        assert_eq!(http_response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_health_response_into_response_unhealthy() {
        let response = HealthResponse {
            status: HealthStatus::Unhealthy,
            checks: vec![],
        };

        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::SERVICE_UNAVAILABLE);
    }

    // ============ BasicHealthCheck tests ============

    #[test]
    fn test_basic_health_check_name() {
        let check = BasicHealthCheck;
        assert_eq!(check.name(), "application");
    }

    #[tokio::test]
    async fn test_basic_health_check_returns_healthy() {
        let check = BasicHealthCheck;
        let result = check.check().await;

        assert_eq!(result.name, "application");
        assert_eq!(result.status, HealthStatus::Healthy);
        assert!(result.message.is_some());
        assert!(result.message.unwrap().contains("running"));
    }

    // ============ HealthChecker tests ============

    #[test]
    fn test_health_checker_new() {
        let checker = HealthChecker::new();
        // Should have the basic health check by default
        assert_eq!(checker.checks.len(), 1);
    }

    #[test]
    fn test_health_checker_default() {
        let checker = HealthChecker::default();
        assert_eq!(checker.checks.len(), 1);
    }

    // Custom health check for testing
    struct MockHealthCheck {
        name: String,
        status: HealthStatus,
        message: Option<String>,
    }

    impl HealthCheck for MockHealthCheck {
        fn name(&self) -> &str {
            &self.name
        }

        fn check(
            &self,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ComponentHealth> + Send + '_>>
        {
            let name = self.name.clone();
            let status = self.status.clone();
            let message = self.message.clone();
            Box::pin(async move {
                ComponentHealth {
                    name,
                    status,
                    message,
                }
            })
        }
    }

    #[test]
    fn test_health_checker_with_check() {
        let checker = HealthChecker::new().with_check(Arc::new(MockHealthCheck {
            name: "database".to_string(),
            status: HealthStatus::Healthy,
            message: None,
        }));

        assert_eq!(checker.checks.len(), 2);
    }

    #[test]
    fn test_health_checker_with_multiple_checks() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "db".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "cache".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "queue".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }));

        assert_eq!(checker.checks.len(), 4); // 1 basic + 3 custom
    }

    #[tokio::test]
    async fn test_health_checker_all_healthy() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "db".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "cache".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }));

        let response = checker.check_health().await;

        assert_eq!(response.status, HealthStatus::Healthy);
        assert_eq!(response.checks.len(), 3);
    }

    #[tokio::test]
    async fn test_health_checker_one_degraded() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "db".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "cache".to_string(),
                status: HealthStatus::Degraded,
                message: Some("High latency".to_string()),
            }));

        let response = checker.check_health().await;

        assert_eq!(response.status, HealthStatus::Degraded);
        assert_eq!(response.checks.len(), 3);
    }

    #[tokio::test]
    async fn test_health_checker_one_unhealthy() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "db".to_string(),
                status: HealthStatus::Unhealthy,
                message: Some("Connection refused".to_string()),
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "cache".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }));

        let response = checker.check_health().await;

        // Unhealthy takes precedence
        assert_eq!(response.status, HealthStatus::Unhealthy);
    }

    #[tokio::test]
    async fn test_health_checker_unhealthy_overrides_degraded() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "service1".to_string(),
                status: HealthStatus::Degraded,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "service2".to_string(),
                status: HealthStatus::Unhealthy,
                message: None,
            }));

        let response = checker.check_health().await;

        // Unhealthy takes precedence over degraded
        assert_eq!(response.status, HealthStatus::Unhealthy);
    }

    #[tokio::test]
    async fn test_health_checker_all_unhealthy() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "db".to_string(),
                status: HealthStatus::Unhealthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "cache".to_string(),
                status: HealthStatus::Unhealthy,
                message: None,
            }));

        let response = checker.check_health().await;

        assert_eq!(response.status, HealthStatus::Unhealthy);
    }

    #[tokio::test]
    async fn test_health_checker_checks_in_order() {
        let checker = HealthChecker::new()
            .with_check(Arc::new(MockHealthCheck {
                name: "first".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }))
            .with_check(Arc::new(MockHealthCheck {
                name: "second".to_string(),
                status: HealthStatus::Healthy,
                message: None,
            }));

        let response = checker.check_health().await;

        // Check order: basic (application), first, second
        assert_eq!(response.checks[0].name, "application");
        assert_eq!(response.checks[1].name, "first");
        assert_eq!(response.checks[2].name, "second");
    }

    // ============ health_handler tests ============

    #[tokio::test]
    async fn test_health_handler() {
        let response = health_handler().await;

        assert_eq!(response.status, HealthStatus::Healthy);
        assert!(!response.checks.is_empty());
        assert_eq!(response.checks[0].name, "application");
    }

    // ============ health_routes tests ============

    #[tokio::test]
    async fn test_health_routes_endpoint() {
        use axum::body::Body;
        use axum::http::Request;
        use tower::ServiceExt;

        let app = health_routes();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let health_response: HealthResponse = serde_json::from_slice(&body).unwrap();

        assert_eq!(health_response.status, HealthStatus::Healthy);
    }

    #[tokio::test]
    async fn test_health_routes_not_found() {
        use axum::body::Body;
        use axum::http::Request;
        use tower::ServiceExt;

        let app = health_routes();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/not-health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}