Skip to main content

harmos_protocol/schema/
identity.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10//! Wire Operation Identities and Executor Admission.
11
12/* === Modules === */
13
14/* === Re-Exports === */
15
16/* === Imports === */
17
18// Standard Library Imports
19
20// Third Party Imports
21
22// Local Imports
23use super::Error;
24
25/* === Constants === */
26
27/* === Macros === */
28
29/* === Type Aliases === */
30
31/* === Structs === */
32
33/* === Enums === */
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum Executor {
37    Plugin,
38    Host,
39}
40
41/* === Traits === */
42
43/* === Implementations === */
44
45/* === Public Functions === */
46
47/// Validate a Wire Operation Identity and Resolve Its Executor.
48pub fn operation_identity(id: &str) -> Result<Executor, Error> {
49    let invalid = || Error(format!("Declare {id}: Use a Valid Operation Identity with a Host or Plugin Executor"));
50    let Some((service, method)) = id.split_once('/') else {
51        let local =
52            id.split('.').all(|segment| !segment.is_empty() && segment.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'));
53        if local {
54            return Ok(Executor::Plugin);
55        }
56        return Err(invalid());
57    };
58    let (package, service) = service.rsplit_once('.').ok_or_else(invalid)?;
59    let identifier = |value: &str| {
60        let mut bytes = value.bytes();
61        let valid_start = bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_');
62        let valid_rest = bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
63        valid_start && valid_rest
64    };
65    let valid_package = package.split('.').all(identifier);
66    let valid_service = identifier(service);
67    let valid_method = identifier(method);
68    if !valid_package || !valid_service || !valid_method {
69        return Err(invalid());
70    }
71    let segments: Vec<_> = package.split('.').collect();
72    let mut executor = None;
73    for (index, segment) in segments.iter().enumerate().skip(1) {
74        let version = segment.strip_prefix('v').is_some_and(|value| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()));
75        if !version {
76            continue;
77        }
78        let selected = match segments[index - 1] {
79            "host" => Executor::Host,
80            "plugin" => Executor::Plugin,
81            _ => continue,
82        };
83        if executor.replace(selected).is_some() {
84            return Err(invalid());
85        }
86    }
87    executor.ok_or_else(invalid)
88}
89
90/// Admit Only Plugin Executor Identities Outside the Library Namespace.
91pub fn plugin_operation_identity(id: &str) -> Result<(), Error> {
92    if operation_identity(id)? != Executor::Plugin {
93        return Err(Error(format!("Register {id}: Serve Operations on the Plugin Executor")));
94    }
95    if id.starts_with("harmos.") || id.starts_with("harmos_") {
96        return Err(Error(format!("Register {id}: Use an Application Namespace; the Host Namespace Is Reserved")));
97    }
98    Ok(())
99}
100
101/* === Private Functions === */
102
103/* === Tests === */
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn wire_identities_resolve_executors_and_reject_missing_executor() {
111        for (id, executor) in [
112            ("example.step.0", Executor::Plugin),
113            ("example.plugin.v1.Lifecycle/Initialize", Executor::Plugin),
114            ("example.plugin.v2.steps.Progress/Get", Executor::Plugin),
115            ("example.host.v1.Prompts/Create", Executor::Host),
116            ("example.host.v1.jobs.Progress/Watch", Executor::Host),
117            ("example.host.v1.jobs.v2.Progress/Watch", Executor::Host),
118        ] {
119            assert_eq!(operation_identity(id).unwrap(), executor);
120            assert_eq!(plugin_operation_identity(id).is_ok(), executor == Executor::Plugin);
121        }
122        for id in [
123            "",
124            ".example",
125            "example..step",
126            "Steps/Execute",
127            "example.values.Steps/Get",
128            "example.model.v1.Steps/Get",
129            "example.host.v1.Steps/",
130            "example.host.v1.Steps/Get/Again",
131            "example.plugin.v1.host.v1.Steps/Get",
132        ] {
133            assert!(operation_identity(id).is_err(), "{id}");
134        }
135        assert!(plugin_operation_identity("harmos.plugin.v1.Instance/Invoke").is_err());
136    }
137}