phoxal 0.4.0

Phoxal — production-oriented autonomous robot framework (engine, model, typed bus, contracts).
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};

use super::{Component, Motion, Role, capability};

const ROBOT_FILE: &str = "robot.yaml";

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Robot {
    pub phoxal: Phoxal,
    pub identity: Identity,
    #[serde(default = "default_structure_path")]
    pub structure: PathBuf,
    pub phoxal_runtimes: PhoxalRuntimes,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub user_runtimes: BTreeMap<String, UserRuntime>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub tools: BTreeMap<String, Tool>,
    pub motion: Motion,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network: Option<Network>,
    pub components: Components,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Phoxal {
    pub cli_min_version: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Identity {
    pub id: String,
    pub namespace: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PhoxalRuntimes {
    pub version: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub overrides: BTreeMap<String, PlatformRuntimeOverride>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PlatformRuntimeOverride {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UserRuntime {
    pub path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tool {
    pub version: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Network {
    #[serde(default)]
    pub uplink: Uplink,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tls: Option<NetworkTls>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Uplink {
    /// Production zenoh endpoints (e.g. "tls/uplink.phoxal.cloud:7447").
    /// Ignored in sim mode - phoxal-cli rewrites the upstream link.
    #[serde(default)]
    pub endpoints: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NetworkTls {
    pub cert: PathBuf,
    pub key: PathBuf,
    pub ca: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Components {
    pub sources: BTreeMap<String, ComponentSource>,
    pub instances: BTreeMap<String, Component>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ComponentSource {
    Git(SourceGit),
    Path(SourcePath),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceGit {
    pub git: String,
    pub tag: String,
    /// Optional subdirectory within the git repository that holds the
    /// component definition (`component.yaml` and friends). Absent means the
    /// component lives at the repository root — the historical single-component
    /// repository layout. A value such as `bno085` selects
    /// `<repo>/bno085/component.yaml`, enabling a shared catalog repository
    /// (e.g. `phoxal/components`) to host many components as subdirectories.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub directory: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourcePath {
    pub path: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
    EmptyIdentityId,
    EmptyIdentityNamespace,
    UnknownPlatformRuntimeOverride {
        name: String,
    },
    UserRuntimeShadowsPlatformRuntime {
        name: String,
    },
    MissingComponentSource {
        instance: String,
        source: String,
    },
    InvalidToken {
        field: String,
        value: String,
    },
    EmptyComponentType {
        instance: String,
    },
    EmptyMountLink {
        instance: String,
    },
    EmptyRoleList {
        instance: String,
        capability: String,
    },
    RepeatedRole {
        instance: String,
        capability: String,
        role: Role,
    },
    InvalidRuntimeClock {
        instance: String,
    },
    InvalidKinematicField {
        field: String,
        message: String,
    },
    InvalidDirectionSign {
        instance: String,
        capability: String,
    },
}

impl Robot {
    pub fn read_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        Self::read_from_string(
            &std::fs::read_to_string(path.join(ROBOT_FILE)).with_context(|| {
                format!(
                    "failed to read robot file {}",
                    path.join(ROBOT_FILE).display()
                )
            })?,
        )
    }

    pub fn read_from_string(string: &str) -> Result<Self> {
        crate::model::robot::Robot::read_from_string(string)
            .map(crate::model::robot::Robot::into_v1)
    }

    pub fn parse_from_dir(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        Self::parse_from_string(
            &std::fs::read_to_string(path.join(ROBOT_FILE)).with_context(|| {
                format!(
                    "failed to read robot file {}",
                    path.join(ROBOT_FILE).display()
                )
            })?,
        )
    }

    pub fn parse_from_string(string: &str) -> Result<Self> {
        crate::model::robot::Robot::parse_from_string(string)
            .map(crate::model::robot::Robot::into_v1)
    }

    pub fn write_to_dir(&self, path: impl AsRef<Path>) -> Result<()> {
        crate::model::robot::Robot::V1(self.clone()).write_to_dir(path)
    }

    pub fn validate(&self) -> std::result::Result<(), Vec<ValidationError>> {
        let mut errors = Vec::new();
        self.validate_basics(&mut errors);
        self.validate_component_sources(&mut errors);
        self.validate_component_structure(&mut errors);
        self.validate_driver_structure(&mut errors);
        self.validate_role_hints(&mut errors);
        self.validate_kinematics(&mut errors);
        self.validate_numerics(&mut errors);
        validation_result(errors)
    }

    pub fn validate_with(
        &self,
        platform_runtime_names: &[&str],
    ) -> std::result::Result<(), Vec<ValidationError>> {
        let mut errors = match self.validate() {
            Ok(()) => Vec::new(),
            Err(errors) => errors,
        };
        let platform_runtime_names = platform_runtime_names
            .iter()
            .copied()
            .collect::<BTreeSet<_>>();

        for runtime_name in self.phoxal_runtimes.overrides.keys() {
            if !platform_runtime_names.contains(runtime_name.as_str()) {
                errors.push(ValidationError::UnknownPlatformRuntimeOverride {
                    name: runtime_name.clone(),
                });
            }
        }
        for runtime_name in self.user_runtimes.keys() {
            if platform_runtime_names.contains(runtime_name.as_str()) {
                errors.push(ValidationError::UserRuntimeShadowsPlatformRuntime {
                    name: runtime_name.clone(),
                });
            }
        }

        validation_result(errors)
    }

    #[must_use]
    pub fn robot_id(&self) -> &str {
        &self.identity.id
    }

    #[must_use]
    pub fn namespace(&self) -> &str {
        &self.identity.namespace
    }

    #[must_use]
    pub fn components(&self) -> &BTreeMap<String, Component> {
        &self.components.instances
    }

    #[must_use]
    pub fn component_instance(&self, component_id: &str) -> Option<&Component> {
        self.components.instances.get(component_id)
    }

    #[must_use]
    pub fn parameter(
        &self,
        capability_ref: &crate::model::component::v1::CapabilityRef,
    ) -> Option<&capability::Parameters> {
        self.component_instance(&capability_ref.component_id)
            .and_then(|component| component.parameters.get(&capability_ref.capability_id))
    }

    #[must_use]
    pub fn used_component_types(&self) -> BTreeSet<&str> {
        self.components
            .instances
            .values()
            .map(|component| component.component.as_str())
            .collect()
    }

    fn validate_basics(&self, errors: &mut Vec<ValidationError>) {
        if self.identity.id.trim().is_empty() {
            errors.push(ValidationError::EmptyIdentityId);
        }
        if self.identity.namespace.trim().is_empty() {
            errors.push(ValidationError::EmptyIdentityNamespace);
        }
    }

    fn validate_component_sources(&self, errors: &mut Vec<ValidationError>) {
        for (instance_name, instance) in &self.components.instances {
            if !self.components.sources.contains_key(&instance.component) {
                errors.push(ValidationError::MissingComponentSource {
                    instance: instance_name.clone(),
                    source: instance.component.clone(),
                });
            }
        }
    }
}

impl Components {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sources.is_empty() && self.instances.is_empty()
    }
}

impl Deref for Components {
    type Target = BTreeMap<String, Component>;

    fn deref(&self) -> &Self::Target {
        &self.instances
    }
}

impl DerefMut for Components {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.instances
    }
}

impl<'a> IntoIterator for &'a Components {
    type Item = (&'a String, &'a Component);
    type IntoIter = std::collections::btree_map::Iter<'a, String, Component>;

    fn into_iter(self) -> Self::IntoIter {
        self.instances.iter()
    }
}

impl<'a> IntoIterator for &'a mut Components {
    type Item = (&'a String, &'a mut Component);
    type IntoIter = std::collections::btree_map::IterMut<'a, String, Component>;

    fn into_iter(self) -> Self::IntoIter {
        self.instances.iter_mut()
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyIdentityId => formatter.write_str("identity.id must not be empty"),
            Self::EmptyIdentityNamespace => {
                formatter.write_str("identity.namespace must not be empty")
            }
            Self::UnknownPlatformRuntimeOverride { name } => write!(
                formatter,
                "phoxal_runtimes.overrides.{name} is not a platform runtime"
            ),
            Self::UserRuntimeShadowsPlatformRuntime { name } => {
                write!(formatter, "user_runtimes.{name} shadows a platform runtime")
            }
            Self::MissingComponentSource { instance, source } => write!(
                formatter,
                "components.instances.{instance}.component references missing source '{source}'"
            ),
            Self::InvalidToken { field, value } => write!(
                formatter,
                "{field} value '{value}' must contain only lowercase ASCII letters, digits, '_' or '-'"
            ),
            Self::EmptyComponentType { instance } => write!(
                formatter,
                "components.instances.{instance}.component must not be empty"
            ),
            Self::EmptyMountLink { instance } => {
                write!(
                    formatter,
                    "components.instances.{instance}.mount_link must not be empty"
                )
            }
            Self::EmptyRoleList {
                instance,
                capability,
            } => write!(
                formatter,
                "components.instances.{instance}.roles.{capability} must list at least one role"
            ),
            Self::RepeatedRole {
                instance,
                capability,
                role,
            } => write!(
                formatter,
                "components.instances.{instance}.roles.{capability} repeats role '{role}'"
            ),
            Self::InvalidRuntimeClock { instance } => write!(
                formatter,
                "components.instances.{instance}.driver.runtime_clock_ms must be > 0"
            ),
            Self::InvalidKinematicField { field, message } => {
                write!(formatter, "motion.kinematic.{field} {message}")
            }
            Self::InvalidDirectionSign {
                instance,
                capability,
            } => write!(
                formatter,
                "components.instances.{instance}.parameters.{capability}.direction_sign must be either -1 or 1"
            ),
        }
    }
}

fn validation_result(
    errors: Vec<ValidationError>,
) -> std::result::Result<(), Vec<ValidationError>> {
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn default_structure_path() -> PathBuf {
    PathBuf::from("structure.urdf")
}