Skip to main content

lean_ctx_cloud/bus/
address.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bus addresses (SPEC-ENGINE §3.7.1, C0 2.0 `bus.schema.json`
3//! `$defs/address`). Only an explicitly addressed message leaves the
4//! machine; no address, `local` or a local agent id stays on the local bus.
5
6use std::fmt;
7
8/// Where a `ctx_agent post` goes.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum Address {
11    /// The local engine bus only (no address, `local`).
12    Local,
13    /// One agent of this machine, by its local bus id.
14    LocalAgent(String),
15    /// `#<workspace>/<vault>`: the vault's bus.
16    Vault { workspace: String, vault: String },
17    /// `@wkr_…`: a direct message to a worker.
18    Worker(String),
19}
20
21/// Why a `#`, `~` or `@` address is refused.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum InvalidAddress {
24    /// Not of the contract grammar.
25    Malformed,
26}
27
28impl fmt::Display for InvalidAddress {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        f.write_str(match self {
31            Self::Malformed => {
32                "invalid_address: use #<workspace>/<vault> or @wkr_<id> (or no address for this machine only)"
33            }
34        })
35    }
36}
37
38impl std::error::Error for InvalidAddress {}
39
40impl Address {
41    /// Parse a `to` argument. `#`, `~` and `@` must be well-formed; any
42    /// other text names a local agent.
43    pub fn parse(to: Option<&str>) -> Result<Self, InvalidAddress> {
44        let Some(to) = to.map(str::trim).filter(|t| !t.is_empty()) else {
45            return Ok(Self::Local);
46        };
47        if to == "local" {
48            return Ok(Self::Local);
49        }
50        if let Some(rest) = to.strip_prefix('#') {
51            let (workspace, vault) = rest.split_once('/').ok_or(InvalidAddress::Malformed)?;
52            let ws_ok = (1..=64).contains(&workspace.len())
53                && workspace.bytes().all(|b| {
54                    b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
55                });
56            if !ws_ok || !slug(vault, 2, 40) {
57                return Err(InvalidAddress::Malformed);
58            }
59            return Ok(Self::Vault {
60                workspace: workspace.to_string(),
61                vault: vault.to_string(),
62            });
63        }
64        if to.starts_with('~') {
65            return Err(InvalidAddress::Malformed);
66        }
67        if let Some(worker) = to.strip_prefix('@') {
68            return is_worker_id(worker)
69                .then(|| Self::Worker(worker.to_string()))
70                .ok_or(InvalidAddress::Malformed);
71        }
72        Ok(Self::LocalAgent(to.to_string()))
73    }
74
75    /// True when the message may leave the machine.
76    pub fn is_remote(&self) -> bool {
77        matches!(self, Self::Vault { .. } | Self::Worker(_))
78    }
79}
80
81impl fmt::Display for Address {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::Local => f.write_str("local"),
85            Self::LocalAgent(id) => f.write_str(id),
86            Self::Vault { workspace, vault } => write!(f, "#{workspace}/{vault}"),
87            Self::Worker(id) => write!(f, "@{id}"),
88        }
89    }
90}
91
92/// `[a-z0-9-]{min,max}`.
93fn slug(s: &str, min: usize, max: usize) -> bool {
94    (min..=max).contains(&s.len())
95        && s.bytes()
96            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
97}
98
99/// A `to` of the contract's `$defs/address` grammar (C0 2.2):
100/// `#<workspace>/<vault>` or `@wkr_<id>`.
101pub fn is_wire_address(to: &str) -> bool {
102    Address::parse(Some(to)).is_ok_and(|a| a.is_remote())
103}
104
105/// `wkr_[a-z2-7]{20}`.
106pub fn is_worker_id(s: &str) -> bool {
107    s.strip_prefix("wkr_").is_some_and(|rest| {
108        rest.len() == 20
109            && rest
110                .bytes()
111                .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
112    })
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn addresses_follow_the_contract_grammar() {
121        assert_eq!(Address::parse(None), Ok(Address::Local));
122        assert_eq!(Address::parse(Some("  ")), Ok(Address::Local));
123        assert_eq!(Address::parse(Some("local")), Ok(Address::Local));
124        assert_eq!(
125            Address::parse(Some("mcp-1-abc")),
126            Ok(Address::LocalAgent("mcp-1-abc".into()))
127        );
128        let vault = Address::parse(Some("#thinkery/lean-ctx")).unwrap();
129        assert_eq!(
130            vault,
131            Address::Vault {
132                workspace: "thinkery".into(),
133                vault: "lean-ctx".into()
134            }
135        );
136        assert_eq!(vault.to_string(), "#thinkery/lean-ctx");
137        assert!(vault.is_remote());
138        assert_eq!(
139            Address::parse(Some("@wkr_vk4oelpv5lzjmev44hun")),
140            Ok(Address::Worker("wkr_vk4oelpv5lzjmev44hun".into()))
141        );
142        assert!(!Address::parse(Some("mcp-1-abc")).unwrap().is_remote());
143        for bad in [
144            "#Thinkery/lean-ctx",
145            "#thinkery",
146            "#thinkery/x",
147            "#thinkery/lean-ctx@cloud.acme.example",
148            "#/lean-ctx",
149            "@wkr_short",
150            "@wkr_vk4oelpv5lzjmev44hu1",
151            "@someone",
152        ] {
153            assert_eq!(
154                Address::parse(Some(bad)),
155                Err(InvalidAddress::Malformed),
156                "{bad}"
157            );
158        }
159    }
160
161    #[test]
162    fn wire_addresses_follow_the_contract_grammar() {
163        for ok in ["#acme/payments", "@wkr_vk4oelpv5lzjmev44hun"] {
164            assert!(is_wire_address(ok), "{ok}");
165        }
166        for bad in [
167            "~checkout-latency",
168            "~ab",
169            "~Launch",
170            "#acme",
171            "@someone",
172            "mcp-1-abc",
173            "local",
174            "",
175        ] {
176            assert!(!is_wire_address(bad), "{bad}");
177        }
178    }
179
180    #[test]
181    fn a_tilde_address_is_invalid() {
182        for bad in ["~launch-q4", "~ab", "~Launch"] {
183            assert_eq!(
184                Address::parse(Some(bad)),
185                Err(InvalidAddress::Malformed),
186                "{bad}"
187            );
188        }
189    }
190}