acton-service 0.21.3

Production-ready Rust backend framework with type-enforced API versioning
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
//! Connection pool health monitoring

use serde::{Deserialize, Serialize};

/// Database connection pool health metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "database")]
pub struct DatabasePoolHealth {
    /// Total number of connections in the pool
    pub size: u32,

    /// Number of idle connections available
    pub idle: usize,

    /// Maximum pool size configured
    pub max_size: u32,

    /// Minimum pool size configured
    pub min_size: u32,

    /// Whether the pool is healthy
    pub healthy: bool,

    /// Pool utilization percentage (0-100)
    pub utilization_percent: f32,
}

#[cfg(feature = "database")]
impl DatabasePoolHealth {
    /// Create health metrics from a PostgreSQL pool
    pub fn from_pool(pool: &sqlx::PgPool, config: &crate::config::DatabaseConfig) -> Self {
        let size = pool.size();
        let idle = pool.num_idle();
        let max_size = config.max_connections;
        let min_size = config.min_connections;

        let utilization_percent = if max_size > 0 {
            ((size as f32 / max_size as f32) * 100.0).min(100.0)
        } else {
            0.0
        };

        // Pool is healthy if not at max capacity
        let healthy = size < max_size;

        Self {
            size,
            idle,
            max_size,
            min_size,
            healthy,
            utilization_percent,
        }
    }
}

/// Redis connection pool health metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "cache")]
pub struct RedisPoolHealth {
    /// Maximum pool size configured
    pub max_size: usize,

    /// Whether the pool is available
    pub available: bool,

    /// Pool status description
    pub status: String,
}

#[cfg(feature = "cache")]
impl RedisPoolHealth {
    /// Create health metrics from a Redis pool
    pub fn from_pool(pool: &deadpool_redis::Pool, config: &crate::config::RedisConfig) -> Self {
        let max_size = config.max_connections;
        let status = pool.status();

        // Pool is available if it's not closed
        let available = status.size > 0 || status.available > 0;

        Self {
            max_size,
            available,
            status: format!("size={}, available={}", status.size, status.available),
        }
    }
}

/// Turso/libsql database health status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "turso")]
pub struct TursoDbHealth {
    /// Connection mode (local, remote, embedded_replica)
    pub mode: String,

    /// Whether the database is connected
    pub connected: bool,

    /// Local database path (for local/embedded_replica modes)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_path: Option<String>,

    /// Remote URL (for remote/embedded_replica modes)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_url: Option<String>,
}

#[cfg(feature = "turso")]
impl TursoDbHealth {
    /// Create health status from Turso config (when connected)
    pub fn from_config(config: &crate::config::TursoConfig, connected: bool) -> Self {
        Self {
            mode: format!("{:?}", config.mode).to_lowercase(),
            connected,
            local_path: config.path.as_ref().map(|p| p.display().to_string()),
            remote_url: config.url.clone(),
        }
    }
}

/// SurrealDB database health status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "surrealdb")]
pub struct SurrealDbHealth {
    /// Connection URL (sanitized, no credentials)
    pub url: String,

    /// SurrealDB namespace
    pub namespace: String,

    /// SurrealDB database
    pub database: String,

    /// Whether the database is connected
    pub connected: bool,
}

#[cfg(feature = "surrealdb")]
impl SurrealDbHealth {
    /// Create health status from SurrealDB config (when connected)
    pub fn from_config(config: &crate::config::SurrealDbConfig, connected: bool) -> Self {
        Self {
            url: crate::surrealdb_backend::sanitize_url(&config.url),
            namespace: config.namespace.clone(),
            database: config.database.clone(),
            connected,
        }
    }
}

/// NATS client health status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "events")]
pub struct NatsClientHealth {
    /// Whether the client is connected
    pub connected: bool,

    /// Server URL
    pub server_url: String,

    /// Client name if configured
    pub client_name: Option<String>,
}

#[cfg(feature = "events")]
impl NatsClientHealth {
    /// Create health status from a NATS client
    pub fn from_client(client: &async_nats::Client, config: &crate::config::NatsConfig) -> Self {
        Self {
            connected: client.connection_state() == async_nats::connection::State::Connected,
            server_url: config.url.clone(),
            client_name: config.name.clone(),
        }
    }
}

/// ClickHouse analytical database health status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "clickhouse")]
pub struct ClickHouseHealth {
    /// Connection URL (sanitized, no credentials)
    pub url: String,

    /// Database name
    pub database: String,

    /// Whether the client is connected
    pub connected: bool,
}

#[cfg(feature = "clickhouse")]
impl ClickHouseHealth {
    /// Create health status from ClickHouse config (when connected)
    pub fn from_config(config: &crate::config::ClickHouseConfig, connected: bool) -> Self {
        Self {
            url: crate::clickhouse_backend::sanitize_url(&config.url),
            database: config.database.clone(),
            connected,
        }
    }
}

/// Overall pool health summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PoolHealthSummary {
    /// Database pool health
    #[cfg(feature = "database")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<DatabasePoolHealth>,

    /// Redis pool health
    #[cfg(feature = "cache")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redis: Option<RedisPoolHealth>,

    /// NATS client health
    #[cfg(feature = "events")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nats: Option<NatsClientHealth>,

    /// Turso/libsql database health
    #[cfg(feature = "turso")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub turso: Option<TursoDbHealth>,

    /// SurrealDB database health
    #[cfg(feature = "surrealdb")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surrealdb: Option<SurrealDbHealth>,

    /// ClickHouse analytical database health
    #[cfg(feature = "clickhouse")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub clickhouse: Option<ClickHouseHealth>,

    /// Overall healthy status
    pub healthy: bool,
}

impl PoolHealthSummary {
    /// Create a new pool health summary
    pub fn new() -> Self {
        Self {
            #[cfg(feature = "database")]
            database: None,
            #[cfg(feature = "cache")]
            redis: None,
            #[cfg(feature = "events")]
            nats: None,
            #[cfg(feature = "turso")]
            turso: None,
            #[cfg(feature = "surrealdb")]
            surrealdb: None,
            #[cfg(feature = "clickhouse")]
            clickhouse: None,
            healthy: true,
        }
    }

    /// Check if all pools are healthy
    pub fn is_healthy(&self) -> bool {
        let database_healthy = {
            #[cfg(feature = "database")]
            {
                self.database.as_ref().is_none_or(|db| db.healthy)
            }
            #[cfg(not(feature = "database"))]
            {
                true
            }
        };

        let cache_healthy = {
            #[cfg(feature = "cache")]
            {
                self.redis.as_ref().is_none_or(|redis| redis.available)
            }
            #[cfg(not(feature = "cache"))]
            {
                true
            }
        };

        let events_healthy = {
            #[cfg(feature = "events")]
            {
                self.nats.as_ref().is_none_or(|nats| nats.connected)
            }
            #[cfg(not(feature = "events"))]
            {
                true
            }
        };

        let turso_healthy = {
            #[cfg(feature = "turso")]
            {
                self.turso.as_ref().is_none_or(|turso| turso.connected)
            }
            #[cfg(not(feature = "turso"))]
            {
                true
            }
        };

        let surrealdb_healthy = {
            #[cfg(feature = "surrealdb")]
            {
                self.surrealdb.as_ref().is_none_or(|s| s.connected)
            }
            #[cfg(not(feature = "surrealdb"))]
            {
                true
            }
        };

        let clickhouse_healthy = {
            #[cfg(feature = "clickhouse")]
            {
                self.clickhouse.as_ref().is_none_or(|ch| ch.connected)
            }
            #[cfg(not(feature = "clickhouse"))]
            {
                true
            }
        };

        database_healthy
            && cache_healthy
            && events_healthy
            && turso_healthy
            && surrealdb_healthy
            && clickhouse_healthy
    }
}

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

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

    #[test]
    fn test_pool_health_summary_default_is_healthy() {
        let summary = PoolHealthSummary::new();
        assert!(summary.is_healthy(), "Empty summary with no backends should be healthy");
    }

    #[cfg(feature = "clickhouse")]
    mod clickhouse_health_tests {
        use super::*;
        use crate::config::ClickHouseConfig;

        fn test_config() -> ClickHouseConfig {
            ClickHouseConfig {
                url: "http://admin:secret@ch.internal:8123".to_string(),
                database: "analytics".to_string(),
                username: Some("admin".to_string()),
                password: Some("secret".to_string()),
                max_retries: 5,
                retry_delay_secs: 2,
                optional: false,
                lazy_init: true,
            }
        }

        #[test]
        fn test_clickhouse_health_from_config_connected() {
            let config = test_config();
            let health = ClickHouseHealth::from_config(&config, true);

            assert!(health.connected);
            assert_eq!(health.database, "analytics");
            // URL must be sanitized — credentials must not appear
            assert!(!health.url.contains("admin"));
            assert!(!health.url.contains("secret"));
            assert!(health.url.contains("ch.internal:8123"));
        }

        #[test]
        fn test_clickhouse_health_from_config_disconnected() {
            let config = test_config();
            let health = ClickHouseHealth::from_config(&config, false);

            assert!(!health.connected);
            assert_eq!(health.database, "analytics");
        }

        #[test]
        fn test_clickhouse_health_serializes_to_json() {
            let config = test_config();
            let health = ClickHouseHealth::from_config(&config, true);
            let json = serde_json::to_value(&health).unwrap();

            assert_eq!(json["connected"], true);
            assert_eq!(json["database"], "analytics");
            assert!(json["url"].is_string());
            // Credentials must not appear in serialized output
            let url_str = json["url"].as_str().unwrap();
            assert!(!url_str.contains("admin"));
            assert!(!url_str.contains("secret"));
        }

        #[test]
        fn test_pool_health_summary_unhealthy_when_clickhouse_disconnected() {
            let mut summary = PoolHealthSummary::new();
            summary.clickhouse = Some(ClickHouseHealth {
                url: "http://ch:8123".to_string(),
                database: "default".to_string(),
                connected: false,
            });

            assert!(
                !summary.is_healthy(),
                "Summary should be unhealthy when ClickHouse is disconnected"
            );
        }

        #[test]
        fn test_pool_health_summary_healthy_when_clickhouse_connected() {
            let mut summary = PoolHealthSummary::new();
            summary.clickhouse = Some(ClickHouseHealth {
                url: "http://ch:8123".to_string(),
                database: "default".to_string(),
                connected: true,
            });

            assert!(
                summary.is_healthy(),
                "Summary should be healthy when ClickHouse is connected"
            );
        }

        #[test]
        fn test_pool_health_summary_healthy_when_clickhouse_none() {
            let summary = PoolHealthSummary::new();
            // clickhouse is None — should not affect health
            assert!(summary.is_healthy());
        }
    }
}