Skip to main content

lenso_process_protocol/
execution_target.rs

1//! Versioned execution-target capability profiles.
2//!
3//! A profile is an Adapter or Driver's explicit, portable declaration of the
4//! interactions and host facilities it implements. It is not an App Plan, a
5//! Plugin requirement, or a provider-selection mechanism. Hosts use it before
6//! composition to reject a selected implementation whose declared target lacks
7//! a required feature.
8
9use serde::{Deserialize, Serialize, de::Error as _};
10
11use super::ProtocolError;
12
13/// Exact versioned profile identity for execution-target capabilities.
14pub const EXECUTION_TARGET_CAPABILITY_PROFILE: &str = "lenso.execution-target-capability-profile@1";
15
16/// Closed feature vocabulary for an execution target.
17///
18/// A future feature is intentionally not accepted by this version. Callers
19/// that ask for an unknown feature therefore receive `false` from
20/// [`ExecutionTargetCapabilityProfile::supports_named`].
21#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
22pub enum ExecutionTargetCapability {
23    /// One request with one terminal outcome.
24    #[serde(rename = "request")]
25    Request,
26    /// One bounded bidirectional Stream session.
27    #[serde(rename = "stream")]
28    Stream,
29    /// Independently admitted volatile Event fan-out.
30    #[serde(rename = "event")]
31    Event,
32    /// WebSocket ingress and lifecycle handling.
33    #[serde(rename = "websocket")]
34    WebSocket,
35    /// Plan-bound guest-to-host imports.
36    #[serde(rename = "host-imports")]
37    HostImports,
38    /// Native child-process execution.
39    #[serde(rename = "native-process")]
40    NativeProcess,
41    /// Wasm component execution.
42    #[serde(rename = "wasm-component")]
43    WasmComponent,
44    /// Remote execution through an Adapter-owned transport.
45    #[serde(rename = "remote")]
46    Remote,
47    /// Browser execution.
48    #[serde(rename = "browser")]
49    Browser,
50    /// Cloudflare Workers execution.
51    #[serde(rename = "workers")]
52    Workers,
53}
54
55impl ExecutionTargetCapability {
56    /// Every feature known to profile version 1, in canonical wire order.
57    pub const ALL: [Self; 10] = [
58        Self::Browser,
59        Self::Event,
60        Self::HostImports,
61        Self::NativeProcess,
62        Self::Remote,
63        Self::Request,
64        Self::Stream,
65        Self::WasmComponent,
66        Self::WebSocket,
67        Self::Workers,
68    ];
69
70    /// Returns the exact portable feature spelling.
71    #[must_use]
72    pub const fn as_str(self) -> &'static str {
73        match self {
74            Self::Request => "request",
75            Self::Stream => "stream",
76            Self::Event => "event",
77            Self::WebSocket => "websocket",
78            Self::HostImports => "host-imports",
79            Self::NativeProcess => "native-process",
80            Self::WasmComponent => "wasm-component",
81            Self::Remote => "remote",
82            Self::Browser => "browser",
83            Self::Workers => "workers",
84        }
85    }
86
87    /// Parses one feature spelling from an untyped request.
88    #[must_use]
89    pub fn from_name(value: &str) -> Option<Self> {
90        match value {
91            "request" => Some(Self::Request),
92            "stream" => Some(Self::Stream),
93            "event" => Some(Self::Event),
94            "websocket" => Some(Self::WebSocket),
95            "host-imports" => Some(Self::HostImports),
96            "native-process" => Some(Self::NativeProcess),
97            "wasm-component" => Some(Self::WasmComponent),
98            "remote" => Some(Self::Remote),
99            "browser" => Some(Self::Browser),
100            "workers" => Some(Self::Workers),
101            _ => None,
102        }
103    }
104}
105
106impl<'de> Deserialize<'de> for ExecutionTargetCapability {
107    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
108    where
109        D: serde::Deserializer<'de>,
110    {
111        let value = String::deserialize(deserializer)?;
112        Self::from_name(&value)
113            .ok_or_else(|| D::Error::custom("unknown execution target capability"))
114    }
115}
116
117/// Machine-checkable declaration of one exact Adapter or Driver target.
118///
119/// `target_profile` identifies the selected runtime profile, for example
120/// `lenso.bun-authoring@2`. It deliberately does not imply any feature: every
121/// supported feature is explicit in `capabilities`.
122#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
123#[serde(deny_unknown_fields)]
124pub struct ExecutionTargetCapabilityProfile {
125    /// Exact versioned profile contract identity.
126    pub profile: String,
127    /// Exact Adapter or Driver runtime profile this declaration describes.
128    pub target_profile: String,
129    /// Canonical-sorted, unique, explicit target features. An empty list is an
130    /// explicit declaration that this target supports no V1 features.
131    pub capabilities: Vec<ExecutionTargetCapability>,
132}
133
134impl ExecutionTargetCapabilityProfile {
135    /// Validates the closed vocabulary, exact profile identity, and canonical
136    /// feature ordering required by the portable profile contract.
137    pub fn validate(&self) -> Result<(), ProtocolError> {
138        if self.profile != EXECUTION_TARGET_CAPABILITY_PROFILE {
139            return Err(ProtocolError::new(
140                "unsupported execution target capability profile",
141            ));
142        }
143        validate_target_profile(&self.target_profile)?;
144        if self
145            .capabilities
146            .windows(2)
147            .any(|pair| pair[0].as_str() >= pair[1].as_str())
148        {
149            return Err(ProtocolError::new(
150                "capabilities must be strictly canonical-sorted and unique",
151            ));
152        }
153        Ok(())
154    }
155
156    /// Returns whether a validated profile explicitly supports this feature.
157    ///
158    /// An invalid or incomplete profile is never trusted, so this method fails
159    /// closed rather than treating its feature list as authoritative.
160    #[must_use]
161    pub fn supports(&self, capability: ExecutionTargetCapability) -> bool {
162        self.validate().is_ok() && self.capabilities.contains(&capability)
163    }
164
165    /// Returns whether a validated profile supports an untyped requested
166    /// feature. Unknown feature names return `false`.
167    #[must_use]
168    pub fn supports_named(&self, capability: &str) -> bool {
169        ExecutionTargetCapability::from_name(capability).is_some_and(|known| self.supports(known))
170    }
171
172    /// Reports every required feature the profile cannot prove it supports.
173    ///
174    /// The result preserves the caller's requirement order. Unknown feature
175    /// names remain missing instead of being silently dropped.
176    #[must_use]
177    pub fn missing_capabilities<'a>(
178        &self,
179        required: impl IntoIterator<Item = &'a str>,
180    ) -> Vec<String> {
181        required
182            .into_iter()
183            .filter(|capability| !self.supports_named(capability))
184            .map(ToOwned::to_owned)
185            .collect()
186    }
187}
188
189fn validate_target_profile(value: &str) -> Result<(), ProtocolError> {
190    if value.is_empty()
191        || value.len() > 128
192        || !value
193            .bytes()
194            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@'))
195    {
196        return Err(ProtocolError::new(
197            "target_profile must be a 1..=128 byte portable token",
198        ));
199    }
200    Ok(())
201}