mecha10-core 0.6.2

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
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
//! Unit tests for Context features that don't require Redis
//!
//! Tests for:
//! - Instance handling
//! - Logging spans
//! - Shutdown mechanism
//! - Node ID handling
//! - Configuration loading (mocked)
//!
//! These tests can run without Redis infrastructure

use std::time::Duration;
use tokio::time::timeout;

// =============================================================================
// Instance Handling Tests
// =============================================================================

#[tokio::test]
async fn test_context_instance_none_by_default() {
    // We can't create a real context without Redis, but we can test the logic
    // through the public API by examining the node_id behavior

    // Test that instance() returns None when not set
    // This would require a mock or test context, so we'll document the expected behavior
    // For now, this is a placeholder for the concept
}

#[tokio::test]
async fn test_instance_name_formatting() {
    // Test that with_instance formats node_id correctly
    // Expected: "node_name/instance"

    // This tests the string formatting logic which is pure
    let base = "camera_node";
    let instance = "left";
    let expected_node_id = format!("{}/{}", base, instance);

    assert_eq!(expected_node_id, "camera_node/left");
}

#[tokio::test]
async fn test_multiple_instance_names() {
    // Test various instance name formats
    let test_cases = vec![
        ("node", "instance1", "node/instance1"),
        ("robot", "left_arm", "robot/left_arm"),
        ("sensor", "camera_0", "sensor/camera_0"),
    ];

    for (base, instance, expected) in test_cases {
        let result = format!("{}/{}", base, instance);
        assert_eq!(result, expected);
    }
}

// =============================================================================
// Shutdown Mechanism Tests
// =============================================================================

#[tokio::test]
async fn test_shutdown_signal_propagation() {
    // Test the shutdown flag behavior
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let shutdown = Arc::new(RwLock::new(false));

    // Initially not shutdown
    assert!(!*shutdown.read().await);

    // Trigger shutdown
    *shutdown.write().await = true;

    // Should be shutdown now
    assert!(*shutdown.read().await);
}

#[tokio::test]
async fn test_shutdown_wait_behavior() {
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let shutdown = Arc::new(RwLock::new(false));
    let shutdown_clone = Arc::clone(&shutdown);

    // Spawn task that will set shutdown after delay
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        *shutdown_clone.write().await = true;
    });

    // Wait for shutdown (with timeout for safety)
    let start = std::time::Instant::now();
    let result = timeout(Duration::from_millis(200), async {
        loop {
            if *shutdown.read().await {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await;

    assert!(result.is_ok());
    let elapsed = start.elapsed();
    assert!(elapsed >= Duration::from_millis(50));
    assert!(elapsed < Duration::from_millis(150));
}

// =============================================================================
// Node ID Tests
// =============================================================================

#[tokio::test]
async fn test_node_id_validation() {
    // Test that node IDs are properly stored and retrieved
    let test_ids = vec!["test-node", "robot_1", "sensor.camera", "node/with/slashes"];

    for id in test_ids {
        // Just verify the string is unchanged
        assert_eq!(id, id);
    }
}

#[tokio::test]
async fn test_consumer_group_naming() {
    // Test consumer group name generation logic
    // Format should be: "{node_id}-{topic_path_with_dashes}"

    let node_id = "test_node";
    let topic_path = "/sensor/camera/rgb";
    let expected = format!("{}-{}", node_id, topic_path.replace('/', "-"));

    assert_eq!(expected, "test_node--sensor-camera-rgb");
}

#[tokio::test]
async fn test_consumer_group_naming_with_instance() {
    // Test consumer group with instance
    let node_id = "camera_node/left";
    let topic_path = "/sensor/lidar";
    let expected = format!("{}-{}", node_id, topic_path.replace('/', "-"));

    assert_eq!(expected, "camera_node/left--sensor-lidar");
}

// =============================================================================
// Topic Path Tests
// =============================================================================

#[tokio::test]
async fn test_scoped_topic_path_generation() {
    // Test instance-scoped topic path logic
    let topic_path = "/sensor/camera/rgb";
    let instance = "left";
    let scoped_path = format!("{}/{}", topic_path, instance);

    assert_eq!(scoped_path, "/sensor/camera/rgb/left");
}

#[tokio::test]
async fn test_scoped_topic_path_no_instance() {
    // When no instance, should return original path
    let topic_path = "/sensor/camera/rgb";
    let instance: Option<&str> = None;

    let scoped_path = if let Some(inst) = instance {
        format!("{}/{}", topic_path, inst)
    } else {
        topic_path.to_string()
    };

    assert_eq!(scoped_path, "/sensor/camera/rgb");
}

#[tokio::test]
async fn test_instance_topic_path_generation() {
    // Test explicit instance topic path
    let topic_path = "/actuator/motor/cmd";
    let instance = "front_left";
    let instance_path = format!("{}/{}", topic_path, instance);

    assert_eq!(instance_path, "/actuator/motor/cmd/front_left");
}

// =============================================================================
// Environment Variable Handling Tests
// =============================================================================

#[tokio::test]
async fn test_redis_url_from_env() {
    // Test Redis URL resolution from environment
    std::env::set_var("REDIS_URL", "redis://custom:6379");

    let url = std::env::var("REDIS_URL").unwrap();
    assert_eq!(url, "redis://custom:6379");

    std::env::remove_var("REDIS_URL");
}

#[tokio::test]
async fn test_redis_url_default() {
    // Test default Redis URL when env var not set
    std::env::remove_var("REDIS_URL");

    let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string());
    assert_eq!(url, "redis://localhost:6379");
}

#[tokio::test]
async fn test_mecha10_environment_variable() {
    // Test environment selection
    std::env::set_var("MECHA10_ENVIRONMENT", "production");

    let env = std::env::var("MECHA10_ENVIRONMENT").unwrap_or_else(|_| "development".to_string());
    assert_eq!(env, "production");

    std::env::remove_var("MECHA10_ENVIRONMENT");
}

#[tokio::test]
async fn test_mecha10_environment_default() {
    std::env::remove_var("MECHA10_ENVIRONMENT");

    let env = std::env::var("MECHA10_ENVIRONMENT").unwrap_or_else(|_| "development".to_string());
    assert_eq!(env, "development");
}

#[tokio::test]
async fn test_state_dir_from_env() {
    std::env::set_var("MECHA10_STATE_DIR", "/custom/state");

    let state_dir = std::env::var("MECHA10_STATE_DIR").unwrap_or_else(|_| "./state".to_string());
    assert_eq!(state_dir, "/custom/state");

    std::env::remove_var("MECHA10_STATE_DIR");
}

// =============================================================================
// Configuration Path Tests
// =============================================================================

#[tokio::test]
async fn test_infrastructure_config_path_generation() {
    // Test config file path generation
    let environments = vec![
        ("development", "config/infrastructure.development.yaml"),
        ("local", "config/infrastructure.local.yaml"),
        ("production", "config/infrastructure.production.yaml"),
    ];

    for (env, expected_path) in environments {
        let path = format!("config/infrastructure.{}.yaml", env);
        assert_eq!(path, expected_path);
    }
}

// =============================================================================
// Logging Span Tests
// =============================================================================

#[tokio::test]
async fn test_logging_span_name() {
    // Test that logging span has correct structure
    // The span should include node_id field

    let node_id = "test_node";

    // Create a span similar to what Context does
    let span = tracing::info_span!("node", node_id = %node_id);

    // Verify span was created (it's a valid span macro call)
    // We can't directly test the name without a subscriber, but this verifies compilation
    let _ = span;
}

// =============================================================================
// Clone Behavior Tests
// =============================================================================

#[tokio::test]
async fn test_arc_clone_behavior() {
    // Test that Arc cloning works as expected for shared state
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let original = Arc::new(RwLock::new(42));
    let cloned = Arc::clone(&original);

    // Modify through clone
    *cloned.write().await = 100;

    // Original should see the change
    assert_eq!(*original.read().await, 100);
}

#[tokio::test]
async fn test_shared_shutdown_flag() {
    // Test that shutdown flag is properly shared via Arc
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let shutdown = Arc::new(RwLock::new(false));
    let shutdown_clone1 = Arc::clone(&shutdown);
    let shutdown_clone2 = Arc::clone(&shutdown);

    // Set via first clone
    *shutdown_clone1.write().await = true;

    // Check via second clone
    assert!(*shutdown_clone2.read().await);

    // Check via original
    assert!(*shutdown.read().await);
}

// =============================================================================
// Infrastructure Config Struct Tests
// =============================================================================

#[tokio::test]
async fn test_redis_config_default() {
    use mecha10_core::context::RedisConfig;

    let config = RedisConfig::default();

    assert_eq!(config.url, "redis://localhost:6379");
    assert_eq!(config.max_connections, 10);
    assert_eq!(config.connection_timeout_ms, 5000);
}

#[tokio::test]
async fn test_redis_config_custom() {
    use mecha10_core::context::RedisConfig;

    let config = RedisConfig {
        url: "redis://custom:6380".to_string(),
        max_connections: 20,
        connection_timeout_ms: 10000,
    };

    assert_eq!(config.url, "redis://custom:6380");
    assert_eq!(config.max_connections, 20);
    assert_eq!(config.connection_timeout_ms, 10000);
}

// =============================================================================
// Topic Discovery Pattern Conversion Tests
// =============================================================================

#[tokio::test]
async fn test_glob_pattern_basic() {
    // Test glob pattern handling (basic validation)
    let patterns = vec![
        ("/sensor/camera/*", true),
        ("/sensor/**", true),
        ("/actuator/motor/*", true),
        ("*", true),
    ];

    for (pattern, _should_be_valid) in patterns {
        // Just verify pattern strings are formed correctly
        assert!(pattern.contains('/') || pattern == "*");
    }
}

// =============================================================================
// Error Handling Tests
// =============================================================================

#[tokio::test]
async fn test_error_message_formatting() {
    use mecha10_core::error::Mecha10Error;

    let error = Mecha10Error::MessagingError {
        message: "Connection failed".to_string(),
        suggestion: "Check Redis is running".to_string(),
    };

    let formatted = format!("{}", error);
    assert!(formatted.contains("Connection failed"));
}

#[tokio::test]
async fn test_configuration_error() {
    use mecha10_core::error::Mecha10Error;

    let error = Mecha10Error::Configuration("Invalid config".to_string());
    let formatted = format!("{}", error);
    assert!(formatted.contains("Invalid config"));
}

// =============================================================================
// Context Builder Tests (Non-Redis)
// =============================================================================

#[tokio::test]
async fn test_context_builder_pattern() {
    use mecha10_core::context::ContextBuilder;

    // Test builder creation (fields are private, just verify it compiles)
    let _builder = ContextBuilder::new("test-node");
    // Builder created successfully
}

#[tokio::test]
async fn test_context_builder_with_instance() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::new("test-node").with_instance("inst1");
    // Builder with instance created successfully
}

#[tokio::test]
async fn test_context_builder_with_redis_url() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::new("test-node").with_redis("redis://custom:6379");
    // Builder with Redis URL created successfully
}

#[tokio::test]
async fn test_context_builder_with_state_dir() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::new("test-node").with_state_dir("/custom/state");
    // Builder with state dir created successfully
}

#[tokio::test]
async fn test_context_builder_local_dev_preset() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::local_dev("dev-node");
    // Local dev builder created successfully
}

#[tokio::test]
async fn test_context_builder_production_preset() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::production("prod-node");
    // Production builder created successfully
}

#[tokio::test]
async fn test_context_builder_test_preset() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::test("test-node");
    // Test builder created successfully
}

#[tokio::test]
async fn test_context_builder_chaining() {
    use mecha10_core::context::ContextBuilder;

    let _builder = ContextBuilder::new("test-node")
        .with_instance("inst1")
        .with_redis("redis://localhost:6379")
        .with_state_dir("./state");

    // Chained builder created successfully
}

// =============================================================================
// Concurrency Tests
// =============================================================================

#[tokio::test]
async fn test_concurrent_shutdown_checks() {
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let shutdown = Arc::new(RwLock::new(false));

    // Spawn multiple readers
    let mut handles = vec![];
    for _ in 0..10 {
        let shutdown_clone = Arc::clone(&shutdown);
        let handle = tokio::spawn(async move { *shutdown_clone.read().await });
        handles.push(handle);
    }

    // All should read false
    for handle in handles {
        assert!(!handle.await.unwrap());
    }
}

#[tokio::test]
async fn test_concurrent_arc_access() {
    use std::sync::Arc;
    use tokio::sync::RwLock;

    let counter = Arc::new(RwLock::new(0));
    let mut handles = vec![];

    // Spawn multiple incrementers
    for _ in 0..10 {
        let counter_clone = Arc::clone(&counter);
        let handle = tokio::spawn(async move {
            *counter_clone.write().await += 1;
        });
        handles.push(handle);
    }

    // Wait for all to complete
    for handle in handles {
        handle.await.unwrap();
    }

    // Should be 10
    assert_eq!(*counter.read().await, 10);
}