mecha10-core 4.2.10

Mecha10 core runtime and foundational types
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
//! Unit tests for node.rs module
//!
//! Tests node lifecycle management including:
//! - NodeImpl trait behavior (init, run, shutdown, health_check)
//! - Graceful and forced shutdown
//! - Error handling during startup and shutdown
//! - RateConfig trait functionality
//! - HealthStatusExt helper methods
//! - HealthReportingConfig
//!
//! # Running Tests
//!
//! ```bash
//! cargo test --package mecha10-core --test node_unit_tests
//! ```

use mecha10_core::prelude::*;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::sleep;

#[derive(Debug, Clone)]
struct SuccessNode {
    #[allow(dead_code)]
    config: SuccessConfig,
    run_count: Arc<AtomicU32>,
    shutdown_count: Arc<AtomicU32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SuccessConfig {
    value: i32,
}

#[async_trait]
impl NodeImpl for SuccessNode {
    type Config = SuccessConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            config,
            run_count: Arc::new(AtomicU32::new(0)),
            shutdown_count: Arc::new(AtomicU32::new(0)),
        })
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        self.run_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        self.shutdown_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        HealthStatus::healthy("SuccessNode is healthy")
    }
}

#[derive(Debug)]
struct FailInitNode;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct FailInitConfig;

#[async_trait]
impl NodeImpl for FailInitNode {
    type Config = FailInitConfig;

    async fn init(_config: Self::Config) -> Result<Self> {
        Err(Mecha10Error::NodeInit("Initialization failed".to_string()))
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        Ok(())
    }
}

#[derive(Debug, Clone)]
struct FailShutdownNode {
    shutdown_error: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct FailShutdownConfig {
    shutdown_error: bool,
}

#[async_trait]
impl NodeImpl for FailShutdownNode {
    type Config = FailShutdownConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            shutdown_error: config.shutdown_error,
        })
    }

    async fn run(&mut self, _ctx: &Context) -> Result<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        if self.shutdown_error {
            Err(Mecha10Error::Shutdown("Shutdown failed".to_string()))
        } else {
            Ok(())
        }
    }
}

#[derive(Debug, Clone)]
struct HealthyNode {
    healthy: Arc<Mutex<bool>>,
    failure_count: Arc<AtomicU32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct HealthyConfig {
    initially_healthy: bool,
}

#[async_trait]
impl NodeImpl for HealthyNode {
    type Config = HealthyConfig;

    async fn init(config: Self::Config) -> Result<Self> {
        Ok(Self {
            healthy: Arc::new(Mutex::new(config.initially_healthy)),
            failure_count: Arc::new(AtomicU32::new(0)),
        })
    }

    async fn run(&mut self, ctx: &Context) -> Result<()> {
        while !ctx.is_shutdown().await {
            sleep(Duration::from_millis(10)).await;
        }
        Ok(())
    }

    async fn health_check(&self) -> HealthStatus {
        let is_healthy = *self.healthy.lock().await;
        if is_healthy {
            HealthStatus {
                healthy: true,
                last_check: now_micros(),
                failure_count: 0,
                message: Some("Node is healthy".to_string()),
            }
        } else {
            let failures = self.failure_count.fetch_add(1, Ordering::SeqCst) + 1;
            HealthStatus {
                healthy: false,
                last_check: now_micros(),
                failure_count: failures,
                message: Some("Node is unhealthy".to_string()),
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RateNodeConfig {
    rate_hz: f32,
}

impl RateConfig for RateNodeConfig {
    fn rate_hz(&self) -> f32 {
        self.rate_hz
    }
}

#[tokio::test]
async fn test_node_init_success() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await;

    assert!(node.is_ok(), "Node initialization should succeed");
    let node = node.unwrap();

    let state = node.state().await;
    assert_eq!(state, NodeState::Starting);
}

#[tokio::test]
async fn test_node_init_failure() {
    let config = FailInitConfig;
    let result = Node::<FailInitNode>::from_config(config).await;

    assert!(result.is_err(), "Node initialization should fail");

    if let Err(e) = result {
        assert!(e.to_string().contains("Initialization failed"));
    }
}

#[tokio::test]
async fn test_node_init_with_config_validation() {
    let config = SuccessConfig { value: 123 };
    let node = Node::<SuccessNode>::from_config(config).await;

    assert!(node.is_ok());
}

#[tokio::test]
async fn test_node_shutdown_success() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let result = node.shutdown().await;

    assert!(result.is_ok());
    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
async fn test_node_shutdown_error_still_transitions() {
    let config = FailShutdownConfig { shutdown_error: true };
    let node = Node::<FailShutdownNode>::from_config(config).await.unwrap();

    let result = node.shutdown().await;

    assert!(result.is_err());
    assert_eq!(node.state().await, NodeState::Stopped);

    if let Err(e) = result {
        assert!(e.to_string().contains("Shutdown failed"));
    }
}

#[tokio::test]
async fn test_node_double_shutdown() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let result1 = node.shutdown().await;
    assert!(result1.is_ok());

    let result2 = node.shutdown().await;
    assert!(result2.is_ok());

    assert_eq!(node.state().await, NodeState::Stopped);
}

#[tokio::test]
async fn test_node_health_check_default() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(health.healthy);
    assert!(health.message.is_some());
}

#[tokio::test]
async fn test_node_health_check_custom() {
    let config = HealthyConfig {
        initially_healthy: true,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(health.healthy);
    assert_eq!(health.failure_count, 0);
}

#[tokio::test]
async fn test_node_health_check_unhealthy() {
    let config = HealthyConfig {
        initially_healthy: false,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    let health = node.health_check().await;

    assert!(!health.healthy);
    assert!(health.failure_count > 0);
}

#[tokio::test]
async fn test_node_health_check_multiple_calls() {
    let config = HealthyConfig {
        initially_healthy: false,
    };
    let node = Node::<HealthyNode>::from_config(config).await.unwrap();

    let health1 = node.health_check().await;
    assert!(!health1.healthy);
    let failures1 = health1.failure_count;

    let health2 = node.health_check().await;
    assert!(!health2.healthy);
    assert!(health2.failure_count > failures1);
}

#[test]
fn test_health_status_ext_healthy() {
    let status = HealthStatus::healthy("All systems operational");

    assert!(status.healthy);
    assert_eq!(status.failure_count, 0);
    assert_eq!(status.message, Some("All systems operational".to_string()));
    assert!(status.last_check > 0);
}

#[test]
fn test_health_status_ext_unhealthy() {
    let status = HealthStatus::unhealthy("Connection failed");

    assert!(!status.healthy);
    assert_eq!(status.failure_count, 1);
    assert_eq!(status.message, Some("Connection failed".to_string()));
    assert!(status.last_check > 0);
}

#[test]
fn test_health_status_ext_with_string() {
    let status = HealthStatus::healthy("OK".to_string());
    assert!(status.healthy);
    assert_eq!(status.message, Some("OK".to_string()));
}

#[test]
fn test_rate_config_rate_hz() {
    let config = RateNodeConfig { rate_hz: 30.0 };
    assert_eq!(config.rate_hz(), 30.0);
}

#[test]
fn test_rate_config_period() {
    let config = RateNodeConfig { rate_hz: 10.0 };
    let period = config.period();

    let expected = Duration::from_millis(100);
    let diff = if period > expected {
        period - expected
    } else {
        expected - period
    };

    assert!(
        diff < Duration::from_micros(1),
        "Period should be approximately 100ms, got {:?}",
        period
    );
}

#[test]
fn test_rate_config_period_high_frequency() {
    let config = RateNodeConfig { rate_hz: 100.0 };
    let period = config.period();

    assert_eq!(period, Duration::from_millis(10));
}

#[tokio::test]
async fn test_rate_config_create_interval() {
    let config = RateNodeConfig { rate_hz: 10.0 };
    let mut interval = config.create_interval();

    let start = Instant::now();
    interval.tick().await;
    interval.tick().await;
    let elapsed = start.elapsed();

    assert!(elapsed >= Duration::from_millis(90));
    assert!(elapsed < Duration::from_millis(150));
}

#[test]
fn test_health_reporting_config_default() {
    let config = HealthReportingConfig::default();

    assert_eq!(config.priority.interval(), Duration::from_secs(5));
    assert!(config.enabled);
}

#[test]
fn test_health_reporting_config_priority_levels() {
    let critical = HealthReportingConfig::critical();
    assert_eq!(critical.priority.interval(), Duration::from_secs(1));
    assert!(critical.enabled);

    let normal = HealthReportingConfig::normal();
    assert_eq!(normal.priority.interval(), Duration::from_secs(5));
    assert!(normal.enabled);

    let background = HealthReportingConfig::background();
    assert_eq!(background.priority.interval(), Duration::from_secs(30));
    assert!(background.enabled);
}

#[test]
fn test_health_reporting_config_clone() {
    let config1 = HealthReportingConfig::critical();
    let config2 = config1.clone();

    assert_eq!(config1.priority.interval(), config2.priority.interval());
    assert_eq!(config1.enabled, config2.enabled);
}

#[tokio::test]
async fn test_node_clone_shares_state() {
    let config = SuccessConfig { value: 42 };
    let node1 = Node::<SuccessNode>::from_config(config).await.unwrap();
    let node2 = node1.clone();

    assert_eq!(node1.state().await, node2.state().await);

    let _ = node1.shutdown().await;

    assert_eq!(node2.state().await, NodeState::Stopped);
}

#[test]
fn test_node_types_are_debug() {
    let config = SuccessConfig { value: 42 };
    let debug_str = format!("{:?}", config);
    assert!(debug_str.contains("SuccessConfig"));
}

#[tokio::test]
async fn test_rapid_node_creation() {
    let mut nodes = Vec::new();

    for i in 0..10 {
        let config = SuccessConfig { value: i };
        let node = Node::<SuccessNode>::from_config(config).await;
        assert!(node.is_ok());
        nodes.push(node.unwrap());
    }

    assert_eq!(nodes.len(), 10);
}

#[tokio::test]
async fn test_rapid_health_checks() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    for _ in 0..100 {
        let health = node.health_check().await;
        assert!(health.healthy);
    }
}

#[tokio::test]
async fn test_rapid_state_queries() {
    let config = SuccessConfig { value: 42 };
    let node = Node::<SuccessNode>::from_config(config).await.unwrap();

    for _ in 0..100 {
        let state = node.state().await;
        assert_eq!(state, NodeState::Starting);
    }
}