Skip to main content

core_api/
extension_sources.rs

1//! Space-owned Integration source selection. A source identity is not authority.
2//! Preview bytes remain on the bound Hub; published bytes remain in the registry.
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6pub const SOURCE_SNAPSHOT_ROUTE: &str = "/dispatch/extension/sources/snapshot";
7pub const ACQUIRE_ROUTE: &str = "/dispatch/extension/acquire";
8pub const RESOURCE_GUIDE_READ_ROUTE: &str = "/dispatch/extension/resources/guides";
9pub const RESOURCE_PLAN_READ_ROUTE: &str = "/dispatch/extension/resources/plan";
10pub const SOURCE_READ_ROUTE: &str = "/dispatch/extension/sources/read";
11pub const MAX_SOURCE_BYTES: usize = 16 * 1024 * 1024;
12pub const MAX_SELECTION_BYTES: usize = 256 * 1024;
13
14/// Exact SHA-256 identity with the same lowercase hexadecimal wire form on both runtimes.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct SnapshotId([u8; 32]);
17
18impl std::str::FromStr for SnapshotId {
19    type Err = &'static str;
20    fn from_str(value: &str) -> Result<Self, Self::Err> {
21        if value.len() != 64
22            || !value
23                .bytes()
24                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
25        {
26            return Err("invalid preview source snapshot");
27        }
28        let mut bytes = [0; 32];
29        for (index, byte) in bytes.iter_mut().enumerate() {
30            *byte = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
31                .map_err(|_| "invalid preview source snapshot")?;
32        }
33        Ok(Self(bytes))
34    }
35}
36impl std::fmt::Display for SnapshotId {
37    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        for byte in self.0 {
39            write!(formatter, "{byte:02x}")?;
40        }
41        Ok(())
42    }
43}
44impl Serialize for SnapshotId {
45    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
46        serializer.collect_str(self)
47    }
48}
49impl<'de> Deserialize<'de> for SnapshotId {
50    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
51        String::deserialize(deserializer)?
52            .parse()
53            .map_err(serde::de::Error::custom)
54    }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase", deny_unknown_fields)]
59pub struct IntegrationSource {
60    pub integration_id: String,
61    /// Registry version, mutually exclusive with Preview content identity.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub version: Option<u32>,
64    #[serde(rename = "type")]
65    pub package_type: PackageType,
66    /// Exact local source manifest digest. Absent for registry-owned releases.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub snapshot: Option<SnapshotId>,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub enum PackageType {
74    Standard,
75    Composite,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "camelCase", deny_unknown_fields)]
80pub struct SpaceSources {
81    pub revision: u64,
82    pub integrations: Vec<IntegrationSource>,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase", deny_unknown_fields)]
87pub struct SourceReadRequest {
88    pub source: IntegrationSource,
89}
90
91/// Only source text and exact script digests cross the compiler callback. Script
92/// bodies are resolved separately on the Hub and never enter the parsed graph.
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase", deny_unknown_fields)]
95pub struct SourceReadResponse {
96    pub source: IntegrationSource,
97    pub schemas: BTreeMap<String, String>,
98    pub script_digests: BTreeMap<String, String>,
99    /// Language tag to intro-translation YAML; English remains in the schema.
100    pub i18n: BTreeMap<String, String>,
101}
102
103impl IntegrationSource {
104    pub fn validate(&self) -> Result<(), &'static str> {
105        let parts: Vec<_> = self.integration_id.split('.').collect();
106        if self.integration_id != "base"
107            && (parts.len() != 2
108                || parts.iter().any(|part| {
109                    part.is_empty()
110                        || !part.as_bytes()[0].is_ascii_alphabetic()
111                        || !part
112                            .bytes()
113                            .all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-')
114                }))
115        {
116            return Err("invalid Integration source identity");
117        }
118        if self.integration_id.len() > 240
119            || self.version.is_some() == self.snapshot.is_some()
120            || self.version.is_some_and(|v| v == 0 || v > i32::MAX as u32)
121        {
122            return Err("invalid Integration source version");
123        }
124        if self.snapshot.is_some()
125            && (self.integration_id == "base" || self.package_type != PackageType::Standard)
126        {
127            return Err("invalid preview source snapshot");
128        }
129        Ok(())
130    }
131}
132
133impl SpaceSources {
134    pub fn validate(&self) -> Result<(), &'static str> {
135        if self.revision > 9_007_199_254_740_991
136            || self.integrations.len() > 1000
137            || (self.revision == 0 && !self.integrations.is_empty())
138        {
139            return Err("invalid Space source snapshot");
140        }
141        let mut sources = std::collections::HashSet::new();
142        for source in &self.integrations {
143            source.validate()?;
144            if !sources.insert((
145                &source.integration_id,
146                source.package_type,
147                source.snapshot.is_some(),
148            )) {
149                return Err("conflicting Integration sources");
150            }
151        }
152        if serde_json::to_vec(self)
153            .map_err(|_| "invalid Space source snapshot")?
154            .len()
155            > MAX_SELECTION_BYTES
156        {
157            return Err("Space source selection exceeds the size limit");
158        }
159        Ok(())
160    }
161
162    /// One effective source per package. Order never changes Preview priority.
163    pub fn resolved(&self) -> Vec<&IntegrationSource> {
164        let mut selected = BTreeMap::new();
165        for source in &self.integrations {
166            let key = (&source.integration_id, source.package_type);
167            if source.snapshot.is_some() || !selected.contains_key(&key) {
168                selected.insert(key, source);
169            }
170        }
171        selected.into_values().collect()
172    }
173}
174
175impl SourceReadResponse {
176    pub fn validate(&self) -> Result<(), &'static str> {
177        self.source.validate()?;
178        if self.schemas.is_empty()
179            || self.schemas.len() > 1000
180            || self.script_digests.len() > 1000
181            || self.i18n.len() > 1000
182        {
183            return Err("invalid Integration source inventory");
184        }
185        for (name, content) in &self.schemas {
186            if name.is_empty()
187                || name.len() > 1024
188                || name.contains(['\\', ':', '\0'])
189                || name
190                    .split('/')
191                    .any(|part| part.is_empty() || part == "." || part == "..")
192                || !(name.ends_with(".yml") || name.ends_with(".yaml"))
193                || content.is_empty()
194            {
195                return Err("invalid Integration source file");
196            }
197        }
198        for (function, digest) in &self.script_digests {
199            if function.is_empty()
200                || function.len() > 128
201                || !function.bytes().enumerate().all(|(i, c)| {
202                    c.is_ascii_alphabetic() || c == b'_' || (i > 0 && c.is_ascii_digit())
203                })
204                || digest.len() != 64
205                || !digest
206                    .bytes()
207                    .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
208            {
209                return Err("invalid Integration script digest");
210            }
211        }
212        for (language, content) in &self.i18n {
213            let mut parts = language.split('-');
214            let first = parts.next().unwrap_or_default();
215            if language == "en"
216                || language.len() > 1024
217                || !(2..=3).contains(&first.len())
218                || !first.bytes().all(|c| c.is_ascii_lowercase())
219                || parts.any(|part| {
220                    !(2..=8).contains(&part.len())
221                        || !part.bytes().all(|c| c.is_ascii_alphanumeric())
222                })
223                || content.is_empty()
224            {
225                return Err("invalid Integration translation source");
226            }
227        }
228        // Bound encoded bytes, including JSON escaping, below the general Bridge
229        // payload ceiling. Large responses use its existing object-store transport.
230        if serde_json::to_vec(self)
231            .map_err(|_| "invalid Integration source")?
232            .len()
233            > MAX_SOURCE_BYTES
234        {
235            return Err("Integration source exceeds the size limit");
236        }
237        Ok(())
238    }
239}