mecha10-core 0.8.0

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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Example usage of JSON Schema Validation for Mecha10 Configuration
//!
//! This example demonstrates how to validate mecha10.json and node configuration
//! files using JSON Schema, catching configuration errors early with helpful messages.

use mecha10::prelude::*;
use serde_json::json;
use std::io::Write;
use tempfile::NamedTempFile;

/// Example 1: Basic project configuration validation
pub fn basic_validation_example() -> Result<()> {
    info!("Example 1: Basic project configuration validation");

    let config = json!({
        "name": "my-robot",
        "version": "1.0.0",
        "description": "Example robot project",
        "author": "Mecha10 Team",
        "robot_id": "robot-001",
        "robot_platform": "differential-drive"
    });

    match validate_project_json(&config) {
        Ok(_) => info!("✓ Valid configuration"),
        Err(e) => error!("✗ Invalid: {}", e),
    }

    Ok(())
}

/// Example 2: Detecting invalid project names
pub fn invalid_name_example() -> Result<()> {
    info!("Example 2: Detecting invalid project names");

    let config = json!({
        "name": "My Robot Project",
        "version": "1.0.0"
    });

    match validate_project_json(&config) {
        Ok(_) => warn!("Unexpectedly passed validation"),
        Err(e) => {
            info!("✓ Correctly caught error:");
            info!("  {}", e);
        }
    }

    Ok(())
}

/// Example 3: Detecting version format errors
pub fn invalid_version_example() -> Result<()> {
    info!("Example 3: Detecting version format errors");

    let config = json!({
        "name": "my-robot",
        "version": "1.0"
    });

    match validate_project_json(&config) {
        Ok(_) => warn!("Unexpectedly passed validation"),
        Err(e) => {
            info!("✓ Correctly caught error:");
            info!("  {}", e);
        }
    }

    Ok(())
}

/// Example 4: Detecting circular dependencies
pub fn circular_dependency_example() -> Result<()> {
    info!("Example 4: Detecting circular dependencies");

    let config = json!({
        "name": "my-robot",
        "version": "1.0.0",
        "nodes": {
            "drivers": [
                {
                    "name": "camera",
                    "path": "./camera",
                    "depends_on": ["lidar"]
                },
                {
                    "name": "lidar",
                    "path": "./lidar",
                    "depends_on": ["imu"]
                },
                {
                    "name": "imu",
                    "path": "./imu",
                    "depends_on": ["camera"]
                }
            ]
        }
    });

    match validate_project_json(&config) {
        Ok(_) => {
            info!("Schema validation passed");

            use mecha10::schema_validation;
            if let Err(e) = schema_validation::validate_project_json(&config)
                .and_then(|_| schema_validation::validate_project_json(&config))
            {
                info!("✓ Correctly caught circular dependency:");
                info!("  {}", e);
            }
        }
        Err(e) => {
            info!("Caught during schema validation: {}", e);
        }
    }

    Ok(())
}

/// Example 5: Detecting undefined run_target references
pub fn undefined_run_target_example() -> Result<()> {
    info!("Example 5: Detecting undefined run_target references");

    let config = json!({
        "name": "my-robot",
        "version": "1.0.0",
        "nodes": {
            "drivers": [
                {
                    "name": "camera",
                    "path": "./camera",
                    "run_target": "nonexistent"
                }
            ]
        },
        "run_targets": {
            "robot": {
                "description": "On-robot execution",
                "resources": {
                    "cpu_limit": "2.0",
                    "memory_limit": "512M"
                }
            },
            "remote": {
                "description": "Cloud execution",
                "resources": {
                    "cpu_limit": "8.0",
                    "memory_limit": "16G"
                }
            }
        }
    });

    info!("This configuration references 'nonexistent' run_target");
    info!("Available targets: robot, remote");

    Ok(())
}

/// Example 6: Detecting duplicate node names
pub fn duplicate_node_names_example() -> Result<()> {
    info!("Example 6: Detecting duplicate node names");

    let config = json!({
        "name": "my-robot",
        "version": "1.0.0",
        "nodes": {
            "drivers": [
                {
                    "name": "camera",
                    "path": "./drivers/camera"
                }
            ],
            "custom": [
                {
                    "name": "camera",
                    "path": "./custom/camera"
                }
            ]
        }
    });

    info!("This configuration has 'camera' defined in both drivers and custom");
    info!("Node names must be unique across all categories");

    Ok(())
}

/// Example 7: Validating file-based configuration
pub fn file_validation_example() -> Result<()> {
    info!("Example 7: Validating file-based configuration");

    let mut temp_file = NamedTempFile::new().map_err(|e| Mecha10Error::IoError(e))?;

    let config_content = json!({
        "$schema": "https://mecha10.dev/schemas/project.schema.json",
        "name": "test-robot",
        "version": "1.0.0",
        "description": "Test robot for validation",
        "robot_id": "${ROBOT_ID}",
        "nodes": {
            "drivers": [
                {
                    "name": "camera_fake",
                    "path": "./drivers/camera_fake",
                    "run_target": "robot",
                    "enabled": true
                }
            ]
        },
        "run_targets": {
            "robot": {
                "description": "Robot",
                "resources": {
                    "cpu_limit": "2.0",
                    "memory_limit": "512M"
                }
            }
        }
    });

    writeln!(temp_file, "{}", serde_json::to_string_pretty(&config_content).unwrap())
        .map_err(|e| Mecha10Error::IoError(e))?;

    match validate_project_config(temp_file.path()) {
        Ok(_) => info!("✓ File validation passed"),
        Err(e) => error!("✗ File validation failed: {}", e),
    }

    Ok(())
}

/// Example 8: Load and validate in one step
pub fn load_and_validate_example() -> Result<()> {
    info!("Example 8: Load and validate in one step");

    let mut temp_file = NamedTempFile::new().map_err(|e| Mecha10Error::IoError(e))?;

    let config_content = json!({
        "name": "rover-robot",
        "version": "1.0.0",
        "description": "Autonomous delivery robot",
        "robot_id": "rover-001",
        "robot_platform": "differential-drive",
        "nodes": {
            "drivers": [
                {
                    "name": "motor_controller",
                    "path": "./drivers/motor",
                    "run_target": "robot"
                },
                {
                    "name": "camera",
                    "path": "./drivers/camera",
                    "run_target": "robot"
                }
            ],
            "custom": [
                {
                    "name": "navigation",
                    "path": "./nodes/navigation",
                    "run_target": "remote",
                    "depends_on": ["motor_controller", "camera"]
                }
            ]
        },
        "run_targets": {
            "robot": {
                "description": "On-robot",
                "resources": {
                    "cpu_limit": "2.0",
                    "memory_limit": "512M"
                }
            },
            "remote": {
                "description": "Cloud",
                "resources": {
                    "cpu_limit": "8.0",
                    "memory_limit": "16G"
                }
            }
        }
    });

    writeln!(temp_file, "{}", serde_json::to_string_pretty(&config_content).unwrap())
        .map_err(|e| Mecha10Error::IoError(e))?;

    match load_and_validate_project(temp_file.path()) {
        Ok(config) => {
            info!("✓ Configuration loaded and validated");
            info!("  Project: {}", config["name"].as_str().unwrap_or("unknown"));
            info!("  Version: {}", config["version"].as_str().unwrap_or("unknown"));

            if let Some(nodes) = config.get("nodes") {
                if let Some(drivers) = nodes.get("drivers").and_then(|d| d.as_array()) {
                    info!("  Drivers: {}", drivers.len());
                }
            }
        }
        Err(e) => error!("✗ Failed: {}", e),
    }

    Ok(())
}

/// Example 9: Validating node configuration
///
/// `validate_node_config_json` (LAB-4066) no longer validates against a generic envelope --
/// every node, built-in or custom, supplies its own schema. This example declares one inline
/// (the shape a real node would normally get from its own `schemars`-derived `Config` struct,
/// via `mecha10-schema-registry`, or a `<name>.schema.json` file for a custom node).
pub fn node_config_validation_example() -> Result<()> {
    info!("Example 9: Validating node configuration");

    let schema = json!({
        "type": "object",
        "required": ["id", "executable"],
        "properties": {
            "id": {"type": "string"},
            "executable": {"type": "string"},
            "mode": {"type": "string", "enum": ["local", "remote", "simulation"]},
            "auto_restart": {"type": "boolean"},
            "health_check_interval_s": {"type": "integer", "minimum": 1, "maximum": 300},
            "publishes": {"type": "array", "items": {"type": "string"}},
            "subscribes": {"type": "array", "items": {"type": "string"}},
            "depends_on": {"type": "array", "items": {"type": "string"}}
        }
    });

    let config = json!({
        "id": "camera_node",
        "executable": "./target/release/camera_node",
        "args": ["--fps", "30"],
        "env": {
            "CAMERA_DEVICE": "/dev/video0"
        },
        "mode": "local",
        "auto_restart": true,
        "health_check_interval_s": 5,
        "publishes": [
            "/sensor/camera/rgb",
            "/sensor/camera/depth"
        ],
        "subscribes": [],
        "depends_on": []
    });

    match validate_node_config_json(&config, &schema) {
        Ok(_) => info!("✓ Node configuration valid"),
        Err(e) => error!("✗ Node configuration invalid: {}", e),
    }

    let invalid_config = json!({
        "id": "bad_node",
        "executable": "./bad_node",
        "mode": "invalid_mode"
    });

    match validate_node_config_json(&invalid_config, &schema) {
        Ok(_) => warn!("Unexpectedly passed validation"),
        Err(e) => {
            info!("✓ Correctly caught invalid mode:");
            info!("  {}", e);
        }
    }

    Ok(())
}

/// Example 10: Exporting schema for IDE integration
pub fn export_schema_example() -> Result<()> {
    info!("Example 10: Exporting schema for IDE integration");

    let temp_dir = std::env::temp_dir();
    let schema_path = temp_dir.join("project.schema.json");

    export_project_schema(&schema_path)?;

    info!("✓ Schema exported to: {:?}", schema_path);
    info!("  You can reference this in your mecha10.json:");
    info!("  {{");
    info!("    \"$schema\": \"file://{}\",", schema_path.display());
    info!("    \"name\": \"my-robot\",");
    info!("    ...");
    info!("  }}");

    if let Ok(schema_content) = std::fs::read_to_string(&schema_path) {
        if let Ok(schema_json) = serde_json::from_str::<serde_json::Value>(&schema_content) {
            info!("  Schema title: {}", schema_json["title"].as_str().unwrap_or(""));
            info!("  Schema ID: {}", schema_json["$id"].as_str().unwrap_or(""));
        }
    }

    Ok(())
}

/// Example 11: Complex configuration with all features
pub fn complex_config_example() -> Result<()> {
    info!("Example 11: Complex configuration with all features");

    let config = json!({
        "$schema": "https://mecha10.dev/schemas/project.schema.json",
        "name": "warehouse-robot",
        "version": "2.1.0-beta",
        "description": "Autonomous warehouse navigation and picking robot",
        "author": "Robotics Team",
        "license": "Apache-2.0",
        "robot_id": "${ROBOT_ID}",
        "robot_platform": "mecanum",
        "nodes": {
            "drivers": [
                {
                    "name": "lidar_sick",
                    "path": "./drivers/lidar_sick",
                    "config": "./config/lidar.yaml",
                    "description": "SICK LiDAR driver for 360° scanning",
                    "run_target": "robot",
                    "enabled": true,
                    "auto_restart": true
                },
                {
                    "name": "motor_odrive",
                    "path": "./drivers/motor_odrive",
                    "config": "./config/motors.yaml",
                    "description": "ODrive motor controller for mecanum drive",
                    "run_target": "robot",
                    "enabled": true,
                    "auto_restart": true
                },
                {
                    "name": "rgbd_camera",
                    "path": "./drivers/rgbd_camera",
                    "config": "./config/camera.yaml",
                    "description": "Intel RealSense D435i RGB-D camera",
                    "run_target": "robot",
                    "enabled": true
                }
            ],
            "custom": [
                {
                    "name": "slam_node",
                    "path": "./nodes/slam",
                    "config": "./config/slam.yaml",
                    "description": "Real-time SLAM and mapping",
                    "run_target": "remote",
                    "enabled": true,
                    "depends_on": ["lidar_sick", "rgbd_camera"]
                },
                {
                    "name": "path_planner",
                    "path": "./nodes/planner",
                    "config": "./config/planner.yaml",
                    "description": "Global and local path planning",
                    "run_target": "remote",
                    "enabled": true,
                    "depends_on": ["slam_node"]
                },
                {
                    "name": "object_detector",
                    "path": "./nodes/detector",
                    "config": "./config/detector.yaml",
                    "description": "ML-based object detection",
                    "run_target": "remote",
                    "enabled": true,
                    "depends_on": ["rgbd_camera"]
                }
            ]
        },
        "run_targets": {
            "robot": {
                "description": "On-robot execution (drivers + low-latency control)",
                "includes": ["robot", "shared"],
                "resources": {
                    "cpu_limit": "4.0",
                    "memory_limit": "2G",
                    "gpu": false,
                    "storage_type": "local",
                    "devices": ["/dev/video0", "/dev/ttyUSB0", "/dev/ttyACM0"]
                }
            },
            "remote": {
                "description": "Cloud/edge execution (compute-intensive tasks)",
                "includes": ["remote", "shared"],
                "resources": {
                    "cpu_limit": "16.0",
                    "memory_limit": "32G",
                    "gpu": {
                        "enabled": true,
                        "vendor": "nvidia",
                        "count": 2
                    },
                    "storage_type": "ssd",
                    "storage_size_gb": 500,
                    "model_cache": "/mnt/models"
                }
            },
            "dev": {
                "description": "Development all-in-one",
                "includes": ["robot", "remote", "shared"],
                "resources": {
                    "cpu_limit": "8.0",
                    "memory_limit": "16G",
                    "gpu": {
                        "enabled": false,
                        "optional": true
                    },
                    "storage_type": "any"
                }
            }
        },
        "behaviors": {
            "default": "./config/behaviors/warehouse.xml",
            "maintenance": "./config/behaviors/maintenance.xml"
        },
        "simulation": {
            "enabled": true,
            "environment": "./environments/warehouse.tscn"
        },
        "scripts": {
            "dev": "cargo run",
            "build": "cargo build --release",
            "test": "cargo test --all",
            "docker:build": "docker-compose build",
            "docker:up": "docker-compose up -d",
            "docker:down": "docker-compose down",
            "deploy": "mecha10 deploy --target production"
        }
    });

    match validate_project_json(&config) {
        Ok(_) => {
            info!("✓ Complex configuration validation passed");
            info!("  Project: warehouse-robot");
            info!("  Drivers: 3");
            info!("  Custom nodes: 3");
            info!("  Run targets: 3 (robot, remote, dev)");
            info!("  All dependencies resolved");
            info!("  No circular dependencies");
        }
        Err(e) => error!("✗ Validation failed: {}", e),
    }

    Ok(())
}

fn main() -> Result<()> {
    tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();

    println!("JSON Schema Validation Usage Examples");
    println!("======================================");
    println!();
    println!("Schema validation catches configuration errors early:");
    println!("1. Invalid project names, versions, node names");
    println!("2. Circular dependencies between nodes");
    println!("3. Undefined run_target references");
    println!("4. Duplicate node names");
    println!("5. Invalid resource specifications");
    println!("6. Missing required fields");
    println!();

    basic_validation_example()?;
    println!();

    invalid_name_example()?;
    println!();

    invalid_version_example()?;
    println!();

    circular_dependency_example()?;
    println!();

    undefined_run_target_example()?;
    println!();

    duplicate_node_names_example()?;
    println!();

    file_validation_example()?;
    println!();

    load_and_validate_example()?;
    println!();

    node_config_validation_example()?;
    println!();

    export_schema_example()?;
    println!();

    complex_config_example()?;
    println!();

    println!("All examples completed!");
    println!();
    println!("Usage in your code:");
    println!("  use mecha10::prelude::*;");
    println!();
    println!("  // Validate project config");
    println!("  validate_project_config(\"mecha10.json\")?;");
    println!();
    println!("  // Load and validate");
    println!("  let config = load_and_validate_project(\"mecha10.json\")?;");
    println!();
    println!("  // Export schema for IDE");
    println!("  export_project_schema(\"project.schema.json\")?;");

    Ok(())
}