mechutil 0.8.8

Utility structures and functions for mechatronics applications.
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
//! Autocore tool & editor registry.
//!
//! External packages contribute **tools and editors** to an autocore
//! installation by shipping a *manifest* file into a drop-in directory
//! (`<config>/tools.d/`). `autocore-server` reads the registry to supervise
//! the tools that are long-running services; `autocore-ide` reads it to learn
//! which module domains have a rich custom editor. Neither hard-codes any
//! knowledge of a specific tool.
//!
//! A manifest describes what a tool *is* and is owned by the installing
//! package (dpkg ships it, dpkg removes it). Mutable, admin-chosen state
//! (the effective port, enabled/disabled, bind address) lives separately in
//! [`crate::tool_settings`] so that package upgrades never clobber it.
//!
//! See `doc/tool-registry.md` for the full contract. The first citizen is
//! `labelit-studio`, the vision-configuration editor for `autocore-labelit`.

use std::fs;
use std::path::{Path, PathBuf};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::paths::resolve_config_dir;

/// Errors from registry operations.
#[derive(Debug, Error)]
pub enum ToolRegistryError {
    #[error("io error on {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("could not parse manifest {path}: {source}")]
    Parse {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },
    #[error("invalid manifest '{name}': {reason}")]
    Validation { name: String, reason: String },
    #[error("no tool named '{0}' is registered")]
    NotFound(String),
}

type Result<T> = std::result::Result<T, ToolRegistryError>;

/// How a tool is launched.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LaunchMode {
    /// Long-running process; `autocore-server` supervises it like a module.
    Service,
    /// Invoked on demand (by the IDE or a CLI); never auto-launched.
    OnDemand,
}

impl Default for LaunchMode {
    fn default() -> Self {
        LaunchMode::OnDemand
    }
}

/// How to launch a tool. Defaults here are *manifest* defaults; the effective
/// port / autostart come from [`crate::tool_settings`].
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LaunchSpec {
    #[serde(default)]
    pub mode: LaunchMode,
    /// Default HTTP port for a service tool that serves a UI.
    #[serde(default)]
    pub default_port: Option<u16>,
    /// Default for whether a service tool starts with the server.
    #[serde(default = "default_true")]
    pub autostart: bool,
    /// Extra arguments inserted before the tool's standard args.
    #[serde(default)]
    pub args: Vec<String>,
}

impl Default for LaunchSpec {
    fn default() -> Self {
        LaunchSpec {
            mode: LaunchMode::default(),
            default_port: None,
            autostart: true,
            args: Vec::new(),
        }
    }
}

/// One config editor a tool contributes, bound to a module domain and
/// optionally a sub-path within that module's config.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EditorContribution {
    /// Module domain this editor edits (e.g. "labelit").
    pub target_domain: String,
    /// JSON pointer into the module config (e.g. "/robot_calibration"), or
    /// `None` for the whole module config.
    #[serde(default)]
    pub target_path: Option<String>,
    /// Human-facing label shown in the IDE (e.g. "Vision Editor").
    pub label: String,
}

/// Contribution metadata for a tool. Shipped by the installing package;
/// read-only at runtime.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ToolManifest {
    /// Manifest format version (currently 1).
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    /// Unique tool id (kebab-case). Matches the manifest's file stem.
    pub name: String,
    /// Tool semver.
    #[serde(default)]
    pub version: String,
    #[serde(default)]
    pub description: Option<String>,
    /// Absolute path to the tool executable.
    pub executable: String,
    /// Whether the tool serves a web UI (drives the security gate and lets a
    /// consumer point a browser / webview at it).
    #[serde(default)]
    pub serves_http: bool,
    /// Root path of the served UI (e.g. "/").
    #[serde(default)]
    pub ui_path: Option<String>,
    #[serde(default)]
    pub launch: LaunchSpec,
    /// Config editors this tool contributes (a tool may contribute several).
    #[serde(default)]
    pub editors: Vec<EditorContribution>,
}

fn default_true() -> bool {
    true
}
fn default_schema_version() -> u32 {
    1
}

/// The current supported manifest `schema_version`.
pub const MANIFEST_SCHEMA_VERSION: u32 = 1;

impl ToolManifest {
    /// Validate structural invariants independent of the filesystem.
    pub fn validate(&self) -> Result<()> {
        let bad = |reason: &str| ToolRegistryError::Validation {
            name: self.name.clone(),
            reason: reason.to_string(),
        };
        if self.name.trim().is_empty() {
            return Err(bad("name is empty"));
        }
        // The name is used as a filename; keep it path-safe.
        if self
            .name
            .contains(['/', '\\', ' ', '.'])
        {
            return Err(bad(
                "name must be kebab-case with no path separators, spaces, or dots",
            ));
        }
        if self.executable.trim().is_empty() {
            return Err(bad("executable is empty"));
        }
        if self.schema_version > MANIFEST_SCHEMA_VERSION {
            return Err(bad(&format!(
                "schema_version {} is newer than supported {}",
                self.schema_version, MANIFEST_SCHEMA_VERSION
            )));
        }
        for e in &self.editors {
            if e.target_domain.trim().is_empty() {
                return Err(bad("an editor contribution has an empty target_domain"));
            }
        }
        Ok(())
    }

    /// True if this tool is a long-running service that the server supervises.
    pub fn is_service(&self) -> bool {
        self.launch.mode == LaunchMode::Service
    }
}

/// The manifests directory, `<config>/tools.d`.
pub fn tools_dir() -> PathBuf {
    resolve_config_dir().join("tools.d")
}

/// Read and parse one manifest file, validating it.
fn read_manifest(path: &Path) -> Result<ToolManifest> {
    let text = fs::read_to_string(path).map_err(|source| ToolRegistryError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let manifest: ToolManifest =
        serde_json::from_str(&text).map_err(|source| ToolRegistryError::Parse {
            path: path.to_path_buf(),
            source,
        })?;
    manifest.validate()?;
    Ok(manifest)
}

/// Load a single tool's manifest by name. Accepts both the flat form
/// (`tools.d/<name>.json`) and the directory form (`tools.d/<name>/manifest.json`).
pub fn load_tool(name: &str) -> Result<ToolManifest> {
    let dir = tools_dir();
    let flat = dir.join(format!("{name}.json"));
    if flat.is_file() {
        return read_manifest(&flat);
    }
    let nested = dir.join(name).join("manifest.json");
    if nested.is_file() {
        return read_manifest(&nested);
    }
    Err(ToolRegistryError::NotFound(name.to_string()))
}

/// List all registered tools. Manifests that fail to parse or validate are
/// skipped with a warning, so one bad file can't hide the rest.
pub fn list_tools() -> Vec<ToolManifest> {
    let dir = tools_dir();
    let mut out = Vec::new();
    let entries = match fs::read_dir(&dir) {
        Ok(e) => e,
        Err(_) => return out, // no registry yet → no tools
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let manifest_path = if path.is_dir() {
            let m = path.join("manifest.json");
            if m.is_file() {
                m
            } else {
                continue;
            }
        } else if path.extension().and_then(|e| e.to_str()) == Some("json") {
            // Skip dotfiles / temp files.
            if path
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.starts_with('.'))
                .unwrap_or(true)
            {
                continue;
            }
            path.clone()
        } else {
            continue;
        };

        match read_manifest(&manifest_path) {
            Ok(m) => {
                let stem = manifest_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("");
                // Lenient on read: warn on a stem/name mismatch but keep the
                // tool (keyed by manifest.name). register_tool is strict.
                if !manifest_path.ends_with("manifest.json") && stem != m.name {
                    log::warn!(
                        "tool manifest {:?}: file stem '{}' does not match name '{}'",
                        manifest_path,
                        stem,
                        m.name
                    );
                }
                out.push(m);
            }
            Err(e) => log::warn!("skipping tool manifest {:?}: {}", manifest_path, e),
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// Find a tool whose editor contributes for `domain` (and, if `path` is given,
/// whose contribution's `target_path` matches). Returns the first match,
/// preferring an exact `target_path` match over a whole-module (`None`) editor.
pub fn find_editor_for(
    domain: &str,
    path: Option<&str>,
) -> Option<(ToolManifest, EditorContribution)> {
    let tools = list_tools();
    let mut whole_module: Option<(ToolManifest, EditorContribution)> = None;
    for tool in tools {
        for editor in &tool.editors {
            if editor.target_domain != domain {
                continue;
            }
            match (&editor.target_path, path) {
                // Exact path match — strongest.
                (Some(tp), Some(p)) if tp == p => {
                    return Some((tool.clone(), editor.clone()));
                }
                // Whole-module editor — remember as a fallback.
                (None, _) => {
                    if whole_module.is_none() {
                        whole_module = Some((tool.clone(), editor.clone()));
                    }
                }
                _ => {}
            }
        }
    }
    whole_module
}

/// Register a tool by writing its manifest into `tools.d/<name>.json`
/// atomically. For tools that are not deb-packaged (dev installs, Windows) and
/// for tests; deb packages ship the manifest as a normal packaged file so the
/// package manager handles register/deregister.
pub fn register_tool(manifest: &ToolManifest) -> Result<()> {
    manifest.validate()?;
    let dir = tools_dir();
    fs::create_dir_all(&dir).map_err(|source| ToolRegistryError::Io {
        path: dir.clone(),
        source,
    })?;
    let dest = dir.join(format!("{}.json", manifest.name));
    let text = serde_json::to_string_pretty(manifest).map_err(|source| {
        ToolRegistryError::Parse {
            path: dest.clone(),
            source,
        }
    })?;
    write_atomic(&dest, text.as_bytes())?;
    Ok(())
}

/// Remove a tool's manifest (flat and directory forms).
pub fn unregister_tool(name: &str) -> Result<()> {
    let dir = tools_dir();
    let flat = dir.join(format!("{name}.json"));
    let nested = dir.join(name);
    let mut removed = false;
    if flat.is_file() {
        fs::remove_file(&flat).map_err(|source| ToolRegistryError::Io {
            path: flat.clone(),
            source,
        })?;
        removed = true;
    }
    if nested.is_dir() {
        fs::remove_dir_all(&nested).map_err(|source| ToolRegistryError::Io {
            path: nested.clone(),
            source,
        })?;
        removed = true;
    }
    if removed {
        Ok(())
    } else {
        Err(ToolRegistryError::NotFound(name.to_string()))
    }
}

/// Write `bytes` to `dest` atomically (temp file in the same directory, then
/// rename), so a reader never sees a half-written manifest.
fn write_atomic(dest: &Path, bytes: &[u8]) -> Result<()> {
    let dir = dest.parent().unwrap_or_else(|| Path::new("."));
    let tmp = dir.join(format!(
        ".{}.tmp.{}",
        dest.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("manifest"),
        std::process::id()
    ));
    fs::write(&tmp, bytes).map_err(|source| ToolRegistryError::Io {
        path: tmp.clone(),
        source,
    })?;
    fs::rename(&tmp, dest).map_err(|source| ToolRegistryError::Io {
        path: dest.to_path_buf(),
        source,
    })?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::paths::test_support::with_temp_config;

    fn sample() -> ToolManifest {
        ToolManifest {
            schema_version: 1,
            name: "labelit-studio".into(),
            version: "1.1.3".into(),
            description: Some("Vision editor".into()),
            executable: "/opt/autocore/bin/modules/labelit-studio".into(),
            serves_http: true,
            ui_path: Some("/".into()),
            launch: LaunchSpec {
                mode: LaunchMode::Service,
                default_port: Some(7878),
                autostart: true,
                args: vec![],
            },
            editors: vec![EditorContribution {
                target_domain: "labelit".into(),
                target_path: None,
                label: "Vision Editor".into(),
            }],
        }
    }

    #[test]
    fn register_list_find_unregister_roundtrip() {
        with_temp_config("roundtrip", || {
            assert!(list_tools().is_empty());

            register_tool(&sample()).unwrap();
            let tools = list_tools();
            assert_eq!(tools.len(), 1);
            assert_eq!(tools[0].name, "labelit-studio");
            assert!(tools[0].is_service());

            // Loads back by name, flat form.
            let loaded = load_tool("labelit-studio").unwrap();
            assert_eq!(loaded.launch.default_port, Some(7878));

            // Editor discovery: whole-module match.
            let (tool, ed) = find_editor_for("labelit", None).expect("editor found");
            assert_eq!(tool.name, "labelit-studio");
            assert_eq!(ed.label, "Vision Editor");
            // A path query still resolves to the whole-module editor fallback.
            assert!(find_editor_for("labelit", Some("/robot_calibration")).is_some());
            // Unknown domain → none.
            assert!(find_editor_for("ethercat", None).is_none());

            unregister_tool("labelit-studio").unwrap();
            assert!(list_tools().is_empty());
            assert!(matches!(
                load_tool("labelit-studio"),
                Err(ToolRegistryError::NotFound(_))
            ));
        });
    }

    #[test]
    fn exact_path_editor_beats_whole_module() {
        with_temp_config("pathmatch", || {
            let mut m = sample();
            m.name = "robot-cal-widget".into();
            m.editors = vec![EditorContribution {
                target_domain: "labelit".into(),
                target_path: Some("/robot_calibration".into()),
                label: "Robot Calibration".into(),
            }];
            register_tool(&m).unwrap();
            register_tool(&sample()).unwrap(); // whole-module labelit editor too

            let (_, ed) =
                find_editor_for("labelit", Some("/robot_calibration")).expect("editor");
            assert_eq!(ed.label, "Robot Calibration");
        });
    }

    #[test]
    fn rejects_invalid_names() {
        with_temp_config("invalid", || {
            let mut m = sample();
            m.name = "has space".into();
            assert!(matches!(
                register_tool(&m),
                Err(ToolRegistryError::Validation { .. })
            ));
        });
    }

    #[test]
    fn bad_manifest_is_skipped_not_fatal() {
        with_temp_config("badfile", || {
            register_tool(&sample()).unwrap();
            // Drop a garbage file alongside a valid one.
            fs::write(tools_dir().join("broken.json"), b"{ not json").unwrap();
            let tools = list_tools();
            assert_eq!(tools.len(), 1, "valid tool survives a broken neighbor");
            assert_eq!(tools[0].name, "labelit-studio");
        });
    }
}